制作networkx图,其中边缘仅显示编辑的数值,而不显示字段名称

Eig*_*lue 2 python matplotlib networkx

显示字段的标签。 可以看到公制和重量

我想要这样做,这样我就可以在重量数字上加上 $ 并将其设置为边缘文本。有聪明人可以告诉我做到这一点的技巧吗?例如,如果边缘的权重为 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()
Run Code Online (Sandbox Code Playgroud)

另外,如果有人可以告诉我如何使文本显示在绘图的前面,IE 文本不会在视觉上被边缘切割,边缘文本如果应该通过它,则位于边缘的顶部。最后,由于某种原因,我的情节标题没有出现。如果有人知道这个问题的解决方案,那就太棒了。多谢你们。总是有很大的帮助。

hit*_*tzg 5

该文档概述了您必须使用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()
Run Code Online (Sandbox Code Playgroud)

编辑:

您无法真正删除轴,因为它们是整个图表的容器。所以人们通常做的就是让刺不可见:

# Axes settings (make the spines invisible, remove all ticks and set title)
ax = plt.gca()
[sp.set_visible(False) for sp in ax.spines.values()]
ax.set_xticks([])
ax.set_yticks([])
Run Code Online (Sandbox Code Playgroud)

设置标题应该很简单:

ax.set_title('This is a nice figure')
# or 
plt.title('This is a nice figure')
Run Code Online (Sandbox Code Playgroud)

结果: 在此输入图像描述