使networkx绘图,其中边只显示编辑的数值,而不显示字段名称

2024-10-01 07:40:25 发布

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

The labels for the fields are displayed. You can see metric and weight

我想让它这样我可以把一个$的重量数字,并设置为边缘文本。有人能告诉我怎么做吗?例如,如果边的权重是20,我希望边文本为“$20”

这是我的密码。在

import json
import networkx as nx
import matplotlib.pyplot as plt
import os
import random
from networkx import graphviz_layout

G=nx.Graph()


for fn in os.listdir(os.getcwd()):
    with open(fn) as data_file:    
        data = json.load(data_file)
        name=data["name"]
        name=name.split(',')
        name = name[1] +  " " + name[0]
        cycle=data["cycle"]
        contributions=data["contributions"]
        contributionListforIndustry=[]
        colorList=[]
        colorList.append((random.uniform(0,1),random.uniform(0,1),random.uniform(0,1)))

        for contibution in contributions:
            amount=contibution["amount"]
            industryName=contibution["name"]
            metric=contibution["metric"]
            colorList.append((random.uniform(0,1),random.uniform(0,1),random.uniform(0,1)))
            contributionListforIndustry.append((industryName,amount))
            G.add_edge(name,industryName,weight=amount, metricval=metric)
        position=nx.graphviz_layout(G,prog='twopi',args='')
        nx.draw(G,position,with_labels=False,node_color=colorList )


        for p in position:  # raise text positions
                t= list(position[p])
                t[1]=t[1]+10
                position[p]=tuple(t)
        nx.draw_networkx_edge_labels(G,position)
        nx.draw_networkx_labels(G, position)
        plt.title("Break down for donations to " + name + " from agriculture industry for " +  str(cycle)  )
        plt.show()

另外,如果有人可以告诉我如何使文本看起来在绘图的前面,即文本没有被边缘可视化地切片,如果边缘文本应该通过边缘,则边缘文本位于边缘的顶部。最后,由于某种原因,我的情节没有出现。如果有人知道解决这个问题的方法,那就太棒了。谢谢各位。总是帮了大忙。在


Tags: name文本importnetworkxfordataasposition
1条回答
网友
1楼 · 发布于 2024-10-01 07:40:25

The documentation概述了必须使用edge_labels参数来指定自定义标签。默认情况下,使用边缘数据的字符串表示。在下面的示例中,创建了这样一个字典:它将边缘元组作为键,格式化字符串作为值。在

要使节点标签更加突出,可以向相应的文本元素添加边界框。您可以在draw_networkx_labels创建它们之后执行此操作:

import matplotlib.pyplot as plt
import networkx as nx

# Define a graph
G = nx.Graph()
G.add_edges_from([(1,2,{'weight':10, 'val':0.1}),
                  (1,4,{'weight':30, 'val':0.3}),
                  (2,3,{'weight':50, 'val':0.5}),
                  (2,4,{'weight':60, 'val':0.6}),
                  (3,4,{'weight':80, 'val':0.8})])
# generate positions for the nodes
pos = nx.spring_layout(G, weight=None)

# create the dictionary with the formatted labels
edge_labels = {i[0:2]:'${}'.format(i[2]['weight']) for i in G.edges(data=True)}

# create some longer node labels
node_labels = {n:"this is node {}".format(n) for n in range(1,5)}


# draw the graph
nx.draw_networkx(G, pos=pos, with_labels=False)

# draw the custom node labels
shifted_pos = {k:[v[0],v[1]+.04] for k,v in pos.iteritems()}
node_label_handles = nx.draw_networkx_labels(G, pos=shifted_pos,
        labels=node_labels)

# add a white bounding box behind the node labels
[label.set_bbox(dict(facecolor='white', edgecolor='none')) for label in
        node_label_handles.values()]

# add the custom egde labels
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)

plt.show()

编辑:

你不能真正地移除轴,因为它们是整个图形的容器。所以人们通常做的就是让脊椎隐形:

^{pr2}$

设置标题应该很简单:

ax.set_title('This is a nice figure')
# or 
plt.title('This is a nice figure')

结果: enter image description here

相关问题 更多 >