今天准备绘制一个饼图,并在旁边放上图例
但发现图例经常会挡住饼图的局部内容,因此将饼图与图例布局成 1行2列的样式:
这种样式可以通过添加两个子图来实现:
fig, axes = plt.subplots(figsize=[7,5] ) # 设置绘图区域大小
#先创建一个绘图区域
ax1 = plt.axes([0.0, 0.0, 0.7, 1])
设置饼状图的绘图区域的范围
此时 执行 axes.axis('off') 是关闭第整个绘图区域的坐标系显示
ax2 = plt.axes([0.75, 0.0, 0.25, 1])
设置图例的绘图区域的范围
此时 执行 ax2.axis('off') 是关闭子图区域的坐标系显示
patches, texts, autotexts = ax1.pie(sizes, labels=labels, autopct='%1.0f%%', shadow=False, startangle=170, colors=colors)
之后在子图1 ax1上绘制饼图
ax2.legend(patches, labels, loc='right')
将饼图的图例显示在子图2 ax2上
完整代码如下
from matplotlib import font_manager as fm
from matplotlib import cm
from matplotlib import font_manager as fm
import matplotlib as mpl
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
# 原始数据
shapes = ['Cross', 'Cone', 'Egg', 'Teardrop', 'Chevron', 'Diamond', 'Cylinder',
'Rectangle', 'Flash', 'Cigar', 'Changing', 'Formation', 'Oval', 'Disk',
'Sphere', 'Fireball', 'Triangle', 'Circle', 'Light']
values = [ 287, 383, 842, 866, 1187, 1405, 1495, 1620, 1717,
2313, 2378, 3070, 4332, 5841, 6482, 7785, 9358, 9818, 20254]
s = pd.Series(values, index=shapes)
s
labels = s.index
sizes = s.values
# explode = (0.2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) # only "explode" the 1st slice
fig, axes = plt.subplots(figsize=[7,5] ) # 设置绘图区域大小
#ax1, ax2 = axes.ravel()
ax1 = plt.axes([0.0, 0.0, 0.7, 1])
#axes.axis('off')
ax2 = plt.axes([0.75, 0.0, 0.25, 1])
ax2.axis('off')
#ax3 = plt.axes([0.75, 0.0, 0.25, 1])
#ax2.axis('off')
axes.axis('off')
# for ax in axes:
# ax.axis('off')
colors = cm.rainbow(np.arange(len(sizes))/len(sizes)) # colormaps: Paired, autumn, rainbow, gray,spring,Darks
patches, texts, autotexts = ax1.pie(sizes, labels=labels, autopct='%1.0f%%',
shadow=False, startangle=170, colors=colors)
ax1.axis('equal')
# 重新设置字体大小
proptease = fm.FontProperties()
proptease.set_size('xx-small')
# font size include: ‘xx-small’,x-small’,'small’,'medium’,‘large’,‘x-large’,‘xx-large’ or number, e.g. '12'
plt.setp(autotexts, fontproperties=proptease)
plt.setp(texts, fontproperties=proptease)
#ax1.set_title('Shapes', loc='center')
# ax2 只显示图例(legend)
ax2.legend(patches, labels, loc='right')
plt.tight_layout()
plt.savefig('Demo_project_set_legend_good.jpg')
plt.show()
画布,图例,子图的概念可参考下面的文章
https://blog.csdn.net/JasonZhu_csdn/article/details/85860963