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)