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

Making networkx plot where edges only display edited numeric value, not field name

我想制作它,这样我就可以在重量数字上放一个 $ 并将其设置为边缘文本。聪明的人可以告诉我这样做的诀窍吗?例如,如果边的权重为 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()

此外,如果有人能告诉我如何让文本显示在图的前面,即文本没有被边缘在视觉上切割,如果边缘文本应该通过,则边缘文本位于边缘之上它。最后,出于某种原因,我的情节的标题没有出现。如果有人也知道解决方案,那就太棒了。多谢你们。总是很有帮助。

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()

编辑:

您不能真正删除 坐标轴,因为它们是整个图表的容器。所以人们通常做的是让刺看不见:

# 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([])

设置标题应该很简单:

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

结果: