【问题标题】:How to wrap marker labels in matplotlib/networkx如何在 matplotlib/networkx 中包装标记标签
【发布时间】:2018-08-21 23:36:25
【问题描述】:

我正在尝试使用 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

如您所见,一些标记标签很长并且被切断了绘图的边缘。有没有办法将这些标签的文本换行以适合绘图区域?

编辑:

数据是一个 45x45 矩阵,来自我使用以下方法导入的 .csv 文件:

network = pd.read_csv('Network.csv')
G = nx.from_numpy_matrix(network.values)
graph_pos = nx.nx_agraph.graphviz_layout(G, prog='neato')

【问题讨论】:

  • 你能把你的数据添加到这个问题吗?
  • 添加了描述 - 需要我将 csv 复制并粘贴到问题中吗?

标签: python-3.x matplotlib networkx


【解决方案1】:

我想出了一个技巧来完成它,但不确定这是否是最好的方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 2018-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    相关资源
    最近更新 更多