原文: https://pythonspot.com/matplotlib-pie-chart/

Matplotlib 使用pie()函数支持饼图。 您可能喜欢 Matplotlib 图库

Matplotlib 饼图

下面的代码创建一个饼图:

  1. import matplotlib.pyplot as plt
  2. # Data to plot
  3. labels = 'Python', 'C++', 'Ruby', 'Java'
  4. sizes = [215, 130, 245, 210]
  5. colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
  6. explode = (0.1, 0, 0, 0) # explode 1st slice
  7. # Plot
  8. plt.pie(sizes, explode=explode, labels=labels, colors=colors,
  9. autopct='%1.1f%%', shadow=True, startangle=140)
  10. plt.axis('equal')
  11. plt.show()

输出:

Matplotlib 饼图 - 图1

python 饼图

要添加图例,请使用plt.legend()函数:

  1. import matplotlib.pyplot as plt
  2. labels = ['Cookies', 'Jellybean', 'Milkshake', 'Cheesecake']
  3. sizes = [38.4, 40.6, 20.7, 10.3]
  4. colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
  5. patches, texts = plt.pie(sizes, colors=colors, shadow=True, startangle=90)
  6. plt.legend(patches, labels, loc="best")
  7. plt.axis('equal')
  8. plt.tight_layout()
  9. plt.show()

输出:

Matplotlib 饼图 - 图2

python 饼图

下载所有 Matplotlib 示例