# Python如何實現餅圖
## 引言
數據可視化是數據分析中不可或缺的一環,而餅圖(Pie Chart)作為最基礎的圖表類型之一,能夠直觀展示各部分占整體的比例關系。Python憑借其豐富的數據可視化庫(如Matplotlib、Seaborn、Plotly等),成為實現餅圖的理想工具。本文將詳細介紹如何用Python主流庫繪制餅圖,涵蓋基礎配置、高級定制以及實際應用場景。
---
## 一、準備工作
### 1.1 安裝必要庫
確保已安裝以下庫(未安裝時通過pip安裝):
```bash
pip install matplotlib pandas plotly
以某公司季度銷售額為例創建數據集:
import pandas as pd
data = {
'Quarter': ['Q1', 'Q2', 'Q3', 'Q4'],
'Sales': [450, 520, 380, 610]
}
df = pd.DataFrame(data)
import matplotlib.pyplot as plt
plt.pie(
df['Sales'],
labels=df['Quarter'],
autopct='%.1f%%'
)
plt.title('Quarterly Sales Distribution')
plt.show()
參數 | 作用 |
---|---|
labels |
設置分類標簽 |
autopct |
顯示百分比格式(如'%.2f%%' 保留兩位小數) |
startangle |
起始角度(默認0度從x軸開始) |
colors |
自定義顏色列表(如['#ff9999','#66b3ff'] ) |
plt.pie(
df['Sales'],
labels=df['Quarter'],
autopct='%1.1f%%',
startangle=90,
shadow=True,
explode=(0.1, 0, 0, 0) # 突出顯示第一塊
)
plt.legend(title="Quarters:")
plt.show()
# 內層數據
inner_data = [200, 250, 180, 300]
plt.pie(df['Sales'], radius=1.2, labels=df['Quarter'], wedgeprops=dict(width=0.3))
plt.pie(inner_data, radius=0.8, wedgeprops=dict(width=0.3))
plt.show()
plt.pie(
df['Sales'],
labels=df['Quarter'],
wedgeprops={'width': 0.4} # 設置環寬
)
plt.title('Donut Chart Example')
plt.show()
import plotly.express as px
fig = px.pie(
df,
values='Sales',
names='Quarter',
hover_data=['Sales'],
hole=0.3 # 環形圖參數
)
fig.update_traces(textposition='inside', textinfo='percent+label')
fig.show()
當比例較小時,可通過以下方式調整:
plt.pie(
df['Sales'],
labels=df['Quarter'],
pctdistance=0.8, # 調整百分比位置
labeldistance=1.1 # 調整標簽位置
)
對小于5%的項合并為”其他”:
threshold = 0.05 * sum(df['Sales'])
filtered = df[df['Sales'] >= threshold]
other = pd.DataFrame({
'Quarter': ['Other'],
'Sales': [sum(df['Sales']) - sum(filtered['Sales'])]
})
new_df = pd.concat([filtered, other])
適用場景:
避免誤區:
視覺優化:
cmap='viridis'
)
wedgeprops={'linewidth': 1, 'edgecolor': 'white'}
# 數據準備
age_data = pd.DataFrame({
'Age Group': ['18-24', '25-34', '35-44', '45+'],
'Users': [1200, 3500, 2400, 900]
})
# 繪制高級餅圖
fig, ax = plt.subplots(figsize=(10,6))
wedges, texts, autotexts = ax.pie(
age_data['Users'],
labels=age_data['Age Group'],
autopct='%.1f%%',
explode=(0, 0.1, 0, 0),
shadow=True,
startangle=140,
colors=['#ff9999','#66b3ff','#99ff99','#ffcc99']
)
# 樣式調整
plt.setp(autotexts, size=10, weight="bold")
ax.set_title("User Age Distribution", pad=20, fontsize=16)
plt.show()
Python實現餅圖既可通過Matplotlib快速完成基礎可視化,也能借助Plotly等庫創建交互式圖表。關鍵在于根據數據特性選擇合適的形式,并通過參數調整提升信息傳達效率。建議讀者結合具體業務場景,靈活運用本文介紹的方法。
擴展學習:
- Matplotlib官方文檔
- Plotly交互式圖表指南 “`
注:本文實際約1800字,可根據需要補充更多代碼示例或理論說明以達到精確字數要求。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。