2

I have the following code that produces an image but the labels are cut off. I edited the first value in each df column on purpose as my real data has really large labels. I tried the plt.tight_layout but it doesnt work.

I also tried the solution from the following link, but was not successful. It only shifted the image to the left.

I also tried increasing the width of the figsize and while it i make it large enough the whole label is shown, the image looks really tiny and stretched out.

I also tried bbox_inches='tight' when saving but the saved image still has cut off labels. I would like to have my labels be fully visible as well as have the left side labels be shifted to the left of the nodes and the right side labels be shifted to the right side of the labels.

import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt

ani_foo = {'Animal': ['CattttttttttttttttttttttttttEND','Cat','Cat','Cat','Cat','Cat','Cat','Cat','Cat','Cat','Dog','Dog','Dog','Dog','Dog','Dog','Dog','Dog','Dog','Snake','Snake','Snake','Snake'],
        'Food': ['Hard_FooddddddddddddddddddddddddEND','Hard_Food','Hard_Food','Hard_Food','Soft_Food','Soft_Food','Soft_Food','Mouse','Soft_Food','Soft_Food','Hard_Food','Hard_Food','Hard_Food','Hard_Food','Soft_Food','Soft_Food','Soft_Food','Soft_Food','Meat','Mouse','Meat','Meat','Meat']
        }

df = pd.DataFrame(ani_foo, columns = ['Animal', 'Food'])

fig, ax = plt.subplots(figsize=(15,8))
G = nx.from_pandas_edgelist(df, 'Animal', 'Food')
G.add_nodes_from(df['Animal'], bipartite=0)
G.add_nodes_from(df['Food'], bipartite=1)
s = df.stack().value_counts()
s1 = s.index +'\n'+ s.astype(str)
pos = {node:[0, i] for i, node in enumerate(df['Animal'])}
pos.update({node:[1,i] for i, node in enumerate(df['Food'])})
color_dict = {'Cat':'g', 'Dog':'b', 'Snake':'y'}
ec = [color_dict[c] for i in G.edges for c in i if c in color_dict.keys()]
nx.draw_networkx(G, 
                 node_size=[s[i]*250 for i in G.nodes], 
                 pos=pos, 
                 labels = s1.to_dict(), 
                 node_color='lightblue',
                 edge_color=ec)
plt.tight_layout
plt.axis('off')

which produces the following undesirable image:

enter image description here

AlmostThere
  • 557
  • 1
  • 11
  • 26
  • 10
    `plt.margins(x=0.4)` creates more space before the first tick and after the last. – JohanC Nov 12 '20 at 13:48
  • Thanks...almost too easy! I actually figured out a very rudimentary way to do by adding "dummy nodes" at 0,0 and 3,0 and coloring them white with white labels and no edges – AlmostThere Nov 12 '20 at 13:52

0 Answers0