networkx标签被切断

时间:2020-11-12 04:39:35

标签: python data-visualization networkx

我有以下代码会生成图像,但标签会被剪切掉。由于我的真实数据具有非常大的标签,因此我有意编辑了每个df列中的第一个值。我尝试了plt.tight_layout,但没有用。

我还尝试了以下link中的解决方案,但未成功。只会将图像向左移动。

我还尝试增加figsize的宽度,虽然将其放大到足以显示整个标签的位置,但是图像看起来确实很小并且被拉长了。

在保存时,我也尝试过bbox_inches='tight',但是保存的图像仍然带有剪切标签。我希望标签完全可见,左侧标签移到节点的左侧,右侧标签移到标签的右侧。

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')

会产生以下不良图像:

enter image description here

0 个答案:

没有答案
相关问题