编程语言
首页 > 编程语言> > python-饼图作为networkx中的节点

python-饼图作为networkx中的节点

作者:互联网

我想知道如何绘制网络(如果可以的话),但是我要用饼图代替圆作为节点,因为我有一个带有社区的图表,我想用工作的人数代表每个人在每个部门.

编辑:
好的,我刚刚尝试了这段代码,结果是好的:

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

我遇到的问题是,当我尝试绘制图例时,我试图将其放置在绘图上方,但它出现在中间.

解决方法:

这是我不久前发布到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')

标签:matplotlib,networkx,pie-chart,python
来源: https://codeday.me/bug/20191029/1956617.html