Matplotlib 饼图
Matplotlib 使用 pie()
函数来绘制饼图。
Matplotlib 饼图
下面的代码创建一个饼图:
import matplotlib.pyplot as plt
labels = 'Python', 'C++', 'Ruby', 'Java'
sizes = [215, 130, 245, 210]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0) # explode 1st slice
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
plt.axis('equal')
plt.show()
输出:
![Matplotlib 饼图](/img/Tutorial/Matplotlib/Matplotlib pie chart.svg)
要添加图例,请使用plt.legend()
函数:
import matplotlib.pyplot as plt
labels = ['Cookies', 'Jellybean', 'Milkshake', 'Cheesecake']
sizes = [38.4, 40.6, 20.7, 10.3]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
patches, texts = plt.pie(sizes, colors=colors, shadow=True, startangle=90)
plt.legend(patches, labels, loc="best")
plt.axis('equal')
plt.tight_layout()
plt.show()
输出:
![Matplotlib 饼图带图例](/img/Tutorial/Matplotlib/Matplotlib pie chart with legend.svg)