我正在尝试使用networkx和matplotlib创建网络图。我有以下代码:
nx.draw_networkx_nodes(G, graph_pos, node_size=node_size,
alpha=node_alpha, node_color=node_color)
nx.draw_networkx_edges(G, graph_pos, width=edge_tickness,
alpha=edge_alpha, edge_color=edge_color)
nx.draw_networkx_labels(G, graph_pos, labels=labels, font_size=node_text_size,
font_family=text_font)
plt.show()
结果如下图: network plot
如您所见,某些标记标签很长,会被切掉绘图的边缘。有什么办法可以将这些标签的文本换行以适合打印区域?
修改:
数据是来自我使用以下命令导入的.csv文件的45x45矩阵:
network = pd.read_csv('Network.csv')
G = nx.from_numpy_matrix(network.values)
graph_pos = nx.nx_agraph.graphviz_layout(G, prog='neato')
答案 0 :(得分:0)
我想出了一个解决办法,尽管不确定这是否是最好的方法:
for l in labels:
if len(labels[l]) > 55:
indices = [i for i, x in enumerate(list(labels[l])) if x == ' ']
indices = np.asarray(indices)
try:
idx = indices[indices > 55][0]
newlabel = list(labels[l])
newlabel.insert(idx, ' \n')
newlabel = ''.join(newlabel)
labels[l] = newlabel
except:
continue