python绘制社会关系网络图,如何添加简单的“颜色栏”在python中绘制网络图?

该博客介绍了如何在使用NetworkX绘制图时添加颜色条。通过提供一个简单的例子,展示了如何利用matplotlib库来实现这一功能,包括设置节点颜色、边的颜色映射以及创建ScalarMappable对象来生成颜色条。尽管`nx.draw`函数本身不返回颜色条,但通过结合使用`plt.colorbar`和`ScalarMappable`,可以成功地在图旁边添加颜色条,从而方便地分析边的颜色含义。
摘要由CSDN通过智能技术生成

I was wondering how can I simply add a colorbar to my plot. I have to following code, which plots a graph by reading a gml file. I have a set of numbers to assign to the edges as their colors and I just want to see a colorbar right next to the plot so I can analyze the colors. When I add the plt.colorbar(g) it gives me error. How can I add a colorbar without going through all the process of actually building the colorbar?

H = nx.read_gml('./network1.gml')

EAM = EigenVectorCentrality( EAMatrix );

x = [];

for eam in EAM[0]:

x.append(eam[0]);

degs = H.degree().values();

plt.clf()

g = nx.draw(H, with_labels=0, edge_color=x, node_size=70, font_size=9, width=1)

plt.axis('equal')

plt.colorbar(g);

plt.show()

And here is the Nerwork1.gml file:

graph

[

node

[

id 1

]

node

[

id 2

]

node

[

id 3

]

node

[

id 4

]

node

[

id 5

]

node

[

id 6

]

node

[

id 7

]

node

[

id 8

]

node

[

id 9

]

node

[

id 10

]

node

[

id 11

]

edge

[

source 1

target 2

]

edge

[

source 1

target 2

]

edge

[

source 1

target 3

]

edge

[

source 1

target 4

]

edge

[

source 1

target 5

]

edge

[

source 2

target 3

]

edge

[

source 2

target 4

]

edge

[

source 2

target 5

]

edge

[

source 3

target 4

]

edge

[

source 3

target 5

]

edge

[

source 4

target 5

]

edge

[

source 6

target 7

]

edge

[

source 6

target 8

]

edge

[

source 6

target 9

]

edge

[

source 6

target 10

]

edge

[

source 7

target 8

]

edge

[

source 7

target 9

]

edge

[

source 7

target 10

]

edge

[

source 8

target 9

]

edge

[

source 8

target 10

]

edge

[

source 9

target 10

]

edge

[

source 5

target 6

]

edge

[

source 5

target 11

]

edge

[

source 6

target 11

]

]

解决方案

Since I did not have your data available, I used this simple example from the networx homepage. But it should be trivial for you to use it in your code.

import matplotlib.pyplot as plt

import networkx as nx

G=nx.star_graph(20)

pos=nx.spring_layout(G)

colors=range(20)

cmap=plt.cm.Blues

vmin = min(colors)

vmax = max(colors)

nx.draw(G, pos, node_color='#A0CBE2', edge_color=colors, width=4, edge_cmap=cmap,

with_labels=False, vmin=vmin, vmax=vmax)

sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin = vmin, vmax=vmax))

sm._A = []

plt.colorbar(sm)

plt.show()

This does the trick, but I agree, it is a bit sad that nx.draw just returns None.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值