实现要点:
argsparser接收数组参数
matplotlib显示中文问题
numpy.random.rand随机产生颜色
import argparse
import matplotlib.pylab as plt
from matplotlib.patches import Wedge,Rectangle
import numpy as np
import matplotlib as mpl
fig,ax=plt.subplots(subplot_kw={"aspect":"equal"})
mpl.rcParams['font.family'] = ['sans-serif']
mpl.rcParams['font.sans-serif'] = ['SimHei']
parser=argparse.ArgumentParser()
parser.add_argument('--items',type=str,nargs="+",help="the items to be painted,expected list")
parser.add_argument('--amount',type=float,nargs="+",help="the amount of the items, expected as list")
args=parser.parse_args()
amount=0
for i in range(len(args.items)):
amount=amount+args.amount[i]
start_angle=45
end_angle=45
wedge=[]
rectangle=[]
start_re=0.1
for i in range(len(args.items)):
color=np.random.rand(4)
end_angle=end_angle+360*args.amount[i]/amount
newWedge=Wedge((2,1.9),1,start_angle,end_angle,facecolor=color,edgecolor=(0,0,0,1))
rectangle.append(Rectangle((3.6, start_re), 0.3, 0.2, color=color))
ax.text(4.2, start_re, "%s:%3.1f%%" %(args.items[i],(args.amount[i] / amount * 100)))
start_re += 0.4
wedge.append(newWedge)
start_angle=end_anglefor re in rectangle:
ax.add_patch(re)
for wed in wedge:
ax.add_patch(wed)
ax.axis([0,8,-0.5,4])
plt.show()
实现效果:
E:\pycharmPro>piePaint.py --items 苹果 梨 葡萄 香蕉 橙子 西瓜 芒果 石榴 --amount 1 2 3 4 5 6 7 8