我想知道如何绘制网络(如果可以的话),但我不想将圆圈作为节点,我想要一个饼图,因为我有一个包含社区的图表,我想用每个数字表示每个在每个部门工作的人。
编辑: 好的,我刚刚尝试了这段代码,结果是Ok:
import community
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import random as rnd
import operator as op
import matplotlib.patches as mpatches
import math
Com = nx.Graph()
Com.add_nodes_from(['0','1','2','3','4'])
comlist=[('0','2',5.0),('3','0',3.0),('1','3',1.0),('2','3',7.3)]
Com.add_weighted_edges_from(comlist)
ListDeps = ['literature','maths','science','physical education']
HistCom = {'0':{'literature':20,
'maths':24,
'science':12},
'1':{'literature':1,
'physical education':14,
'science':6},
'2':{'science':15},
'3':{'physical education':4,
'maths':20},
'4':{'literature':20,
'maths':24,
'science':12}}
pos=nx.spring_layout(Com)
fig=plt.figure(figsize=(5,5))
ax=plt.axes([0,0,1,1])
ax.set_aspect('equal')
nx.draw_networkx_edges(Com,pos,ax=ax)
plt.xlim(-0.5,1.5)
plt.ylim(-0.5,1.5)
trans=ax.transData.transform
trans2=fig.transFigure.inverted().transform
piesize=0.1 #Degree
p2=piesize/2.0
dep_color = dict()
for com in Com:
xx,yy=trans(pos[com]) # figure coordinates
xa,ya=trans2((xx,yy)) # axes coordinates
a = plt.axes([xa-p2,ya-p2, piesize, piesize])
a.set_aspect('equal')
contats = len(HistCom[com].items())
fracs = []
ColorFrac = []
for dep,n in sorted(HistCom[com].items(), key=op.itemgetter(1), reverse=True):
fracs.append(n/sum(HistCom[com].values()))
dep_color[dep] = dep_color.get(dep, (rnd.random(),rnd.random(),rnd.random()))
ColorFrac.append(dep_color[dep])
a.pie(fracs, colors = ColorFrac)
P = [mpatches.Patch(color=dep_color[dep], label=dep) for dep in dep_color]
plt.legend(handles=P,bbox_to_anchor=(0.,1.02,1.,.102), loc=3,ncol=3, mode="expand", borderaxespad=0.)
plt.show()
我遇到的问题是当我试图绘制图例时,我试图把它放在图上方,但它出现在中间。
答案 0 :(得分:4)
这是我前一段时间发布到networkx-discuss邮件列表的内容。 "变换"部分不太正确(需要matplotlib专家)所以缩放不能正常工作。但这是一个开始,
import networkx as nx
import matplotlib.pyplot as plt
G=nx.complete_graph(4)
pos=nx.spring_layout(G)
fig=plt.figure(figsize=(5,5))
ax=plt.axes([0,0,1,1])
ax.set_aspect('equal')
nx.draw_networkx_edges(G,pos,ax=ax)
plt.xlim(-0.5,1.5)
plt.ylim(-0.5,1.5)
trans=ax.transData.transform
trans2=fig.transFigure.inverted().transform
piesize=0.2
p2=piesize/2.0
for n in G:
xx,yy=trans(pos[n]) # figure coordinates
xa,ya=trans2((xx,yy)) # axes coordinates
a = plt.axes([xa-p2,ya-p2, piesize, piesize])
a.set_aspect('equal')
fracs = [15,30,45, 10]
a.pie(fracs)
plt.savefig('pc.png')