networkx label being cutoff

為{幸葍}努か 提交于 2021-01-29 11:27:46

问题


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:

来源:https://stackoverflow.com/questions/64798027/networkx-label-being-cutoff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!