繪製長條圖
# 使用 Matplotlib 繪製長條圖
Matplotlib 中常用 `plt.bar()` 或 `ax.bar()` 繪製垂直長條圖,基本語法如下:
```python
plt.bar(x, height)
```
其中:
- `x`:長條的位置或類別
- `height`:每個長條的數值
- `width`:長條寬度,預設約為 `0.8`
- `color`:長條顏色
- `edgecolor`:邊框顏色
- `alpha`:透明度,範圍為 `0 ~ 1`
- `label`:圖例名稱
建議使用物件導向寫法:
```python
fig, ax = plt.subplots()
ax.bar(...)
```
這種寫法在需要繪製多張圖或設定多個座標軸時較容易管理。
---
## 範例一:繪製基本長條圖
```python
import matplotlib.pyplot as plt
# 資料
products = ["A", "B", "C", "D"]
sales = [120, 180, 150, 220]
# 建立圖表
fig, ax = plt.subplots(figsize=(8, 5))
# 繪製長條圖
bars = ax.bar(
products,
sales,
color="skyblue",
edgecolor="black",
width=0.6
)
# 設定標題與座標軸標籤
ax.set_title("Product Sales", fontsize=16)
ax.set_xlabel("Product")
ax.set_ylabel("Sales")
# 設定 Y 軸範圍
ax.set_ylim(0, 250)
# 顯示水平網格線
ax.grid(axis="y", linestyle="--", alpha=0.5)
# 在長條上方顯示數值
for bar in bars:
height = bar.get_height()
ax.text(
bar.get_x() + bar.get_width() / 2,
height + 5,
str(height),
ha="center",
va="bottom"
)
# 自動調整版面並顯示
plt.tight_layout()
plt.show()
```
### 說明
- `figsize=(8, 5)`:設定圖表大小。
- `color="skyblue"`:設定長條顏色。
- `edgecolor="black"`:設定長條邊框。
- `ax.set_ylim(0, 250)`:設定 Y 軸顯示範圍。
- `ax.grid(axis="y")`:只顯示 Y 軸方向的網格線。
- `ax.text()`:在每個長條上方加入數值標籤。
---
## 範例二:繪製群組長條圖
以下比較兩個季度中,各產品的銷售量。
```python
import matplotlib.pyplot as plt
import numpy as np
# 資料
products = ["A", "B", "C", "D"]
quarter_1 = [120, 180, 150, 220]
quarter_2 = [140, 160, 190, 200]
# 每個產品在 X 軸上的位置
x = np.arange(len(products))
# 長條寬度
width = 0.35
# 建立圖表
fig, ax = plt.subplots(figsize=(8, 5))
# 繪製兩組長條
bars1 = ax.bar(
x - width / 2,
quarter_1,
width,
label="Quarter 1",
color="cornflowerblue"
)
bars2 = ax.bar(
x + width / 2,
quarter_2,
width,
label="Quarter 2",
color="orange"
)
# 設定 X 軸刻度與標籤
ax.set_xticks(x)
ax.set_xticklabels(products)
# 設定標題與座標軸
ax.set_title("Quarterly Product Sales", fontsize=16)
ax.set_xlabel("Product")
ax.set_ylabel("Sales")
# 顯示圖例與網格
ax.legend()
ax.grid(axis="y", linestyle="--", alpha=0.5)
# 在長條上方顯示數值
ax.bar_label(bars1, padding=3)
ax.bar_label(bars2, padding=3)
plt.tight_layout()
plt.show()
```
### 群組長條圖的重點
```python
x = np.arange(len(products))
```
建立每個產品的位置,例如:
```python
[0, 1, 2, 3]
```
接著讓兩組資料分別向左、向右移動:
```python
x - width / 2
x + width / 2
```
這樣兩組長條就能並排顯示。
---
## 常用設定整理
### 1. 設定長條顏色
```python
ax.bar(x, values, color="green")
```
也可以為每個長條指定不同顏色:
```python
colors = ["red", "blue", "green", "orange"]
ax.bar(x, values, color=colors)
```
### 2. 設定座標軸刻度
```python
ax.set_xticks([0, 1, 2])
ax.set_xticklabels(["一月", "二月", "三月"])
```
### 3. 旋轉刻度標籤
當類別名稱較長時,可以旋轉文字:
```python
plt.xticks(rotation=45)
```
或:
```python
ax.tick_params(axis="x", rotation=45)
```
### 4. 繪製水平長條圖
使用 `barh()`:
```python
ax.barh(products, sales)
```
水平長條圖適合用於類別名稱較長的情況。
### 5. 儲存圖片
```python
plt.savefig("bar_chart.png", dpi=300, bbox_inches="tight")
```
- `dpi=300`:設定圖片解析度。
- `bbox_inches="tight"`:避免標籤被裁切。
### 6. 顯示中文
如果系統沒有適合的中文字型,中文可能顯示成方框,可設定字型,例如:
```python
plt.rcParams["font.sans-serif"] = ["Microsoft JhengHei"]
plt.rcParams["axes.unicode_minus"] = False
```
Windows 常見的中文字型是 `Microsoft JhengHei`;macOS 可嘗試使用 `PingFang TC`。
相關學習地圖、教學課程
Python 資料工程