如何使节点标签在matplotlib中更可见

2024-03-28 23:39:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我用networkxmatplotlib绘制网络图。我为每个节点关联了一个浮点数形式的标签(最多两个小数点)。我希望标签在图表中更清晰可见。有没有什么方法可以让标签更清晰?在

Matplotlib Graph

更新: 我发现了一个类似的问题here,并尝试应用解决方案。事实证明,这个解决方案的效果相当糟糕。在

MatplotLib Attempt at a Solution

代码如下:

label_ratio = 1.0/8.0
    pos_labels = {} 
    #For each node in the Graph
    for node in network.graph.nodes():
        #Get the node's position from the layout
        x,y = network.position[node]
        #Get the node's neighbourhood
        N = network.graph[node]
        #Find the centroid of the neighbourhood. The centroid is the average of the Neighbourhood's node's x and y coordinates respectively.
        #Please note: This could be optimised further
        cx = sum(map(lambda x:pos[x][0], N)) / len(pos)
        cy = sum(map(lambda x:pos[x][1], N)) / len(pos)
        #Get the centroid's 'direction' or 'slope'. That is, the direction TOWARDS the centroid FROM aNode.
        slopeY = (y-cy)
        slopeX = (x-cx)
        #Position the label at some distance along this line. Here, the label is positioned at about 1/8th of the distance.
        pos_labels[node] = (x+slopeX*label_ratio, y+slopeY*label_ratio)

nx.draw(G, pos, ax=axis, node_size=20, with_labels=False)
nx.draw_networkx_labels(G, pos_labels, labels, font_size=7, font_color='b', ax=axis)

Tags: oftheinposnetworkxnodegetlabels
1条回答
网友
1楼 · 发布于 2024-03-28 23:39:27

NetworkX的功能不足以绘制大型图形,因为它只提供可视化图形的基本功能。在

在您的例子中,增加节点大小似乎不可避免地会使节点标签更加可见。一旦尺寸增大,就会出现相对位置的问题。我建议你先用Gephi做个更好的布局。在

以下是基本步骤。在

  • 第1步。将NetworkX图形导出为适当的格式,例如.gramph
  • 第二步。Gephi布局
  • 第三步。使用Matplotlib打印或直接从Gephi导出

详细说明请参考NetworkX Application Notes: A better way to visualize graphs


使用提问者提供的图形文件,从Gephi导出下图(使用布局YifanHu,手动拖动一些节点,>;预览(例如调整文本大小)>;导出)。它比NetworkX好吗?在

enter image description here

相关问题 更多 >