# Matplotlib如何調整圖例
## 1. 引言
在數據可視化中,圖例(Legend)是幫助讀者理解圖表內容的關鍵元素。Matplotlib作為Python最流行的繪圖庫之一,提供了豐富的圖例自定義功能。本文將詳細介紹如何通過Matplotlib調整圖例的位置、樣式、內容等,涵蓋基礎設置到高級技巧。
## 2. 基礎圖例創建
### 2.1 自動生成圖例
最簡單的圖例創建方式是使用`plt.legend()`函數:
```python
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x), label='sin(x)')
plt.plot(x, np.cos(x), label='cos(x)')
plt.legend() # 自動生成圖例
plt.show()
也可以通過label
參數顯式指定:
lines = plt.plot(x, np.sin(x), x, np.cos(x))
plt.legend(lines, ['Sine', 'Cosine'])
通過loc
參數指定位置,支持數值和字符串兩種形式:
plt.legend(loc='upper right') # 右上角
plt.legend(loc=1) # 等價寫法
常用位置參數:
- 'best'
(0): 自動選擇最佳位置
- 'upper right'
(1)
- 'upper left'
(2)
- 'lower left'
(3)
- 'lower right'
(4)
- 'right'
(5)
- 'center left'
(6)
- 'center right'
(7)
- 'lower center'
(8)
- 'upper center'
(9)
- 'center'
(10)
使用bbox_to_anchor
參數實現更靈活的位置控制:
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.legend(
frameon=True, # 顯示邊框
framealpha=0.8, # 透明度
facecolor='lightgray', # 背景色
edgecolor='black' # 邊框顏色
)
plt.legend(
title='Functions', # 圖例標題
title_fontsize='large', # 標題字號
fontsize=10, # 標簽字號
prop={'family': 'serif'} # 字體
)
plt.legend(
ncol=2, # 分2列顯示
columnspacing=1.5, # 列間距
handlelength=2, # 圖例句柄長度
handletextpad=0.5 # 句柄與文本間距
)
lines = plt.plot(x, np.sin(x), x, np.cos(x))
plt.legend([lines[0]], ['Sine']) # 只顯示第一條線
from matplotlib.lines import Line2D
custom_lines = [Line2D([0], [0], color='red', lw=2),
Line2D([0], [0], color='blue', lw=2)]
plt.legend(custom_lines, ['Class 1', 'Class 2'])
from matplotlib.legend import Legend
fig, ax = plt.subplots()
line1, = ax.plot(x, np.sin(x))
line2, = ax.plot(x, np.cos(x))
leg1 = Legend(ax, [line1], ['Sine'], loc='upper right')
leg2 = Legend(ax, [line2], ['Cosine'], loc='lower right')
ax.add_artist(leg1)
ax.add_artist(leg2)
使用bbox_extra_artists
和bbox_inches
保存完整圖例:
plt.savefig('plot.png', bbox_extra_artists=(legend,), bbox_inches='tight')
調整圖形大小或使用tight_layout()
:
plt.figure(figsize=(8, 6))
plt.tight_layout()
使用legend()
的borderaxespad
參數:
plt.legend(loc='upper left', borderaxespad=0.5)
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('seaborn')
x = np.linspace(0, 10, 200)
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(x, np.sin(x), label='Sine', color='royalblue', linestyle='--')
ax.plot(x, np.cos(x), label='Cosine', color='crimson', linewidth=2)
ax.plot(x, 0.5*np.sin(x), label='Half Sine', color='green', alpha=0.6)
legend = ax.legend(
loc='upper center',
bbox_to_anchor=(0.5, 1.15),
ncol=3,
fancybox=True,
shadow=True,
title='Trigonometric Functions',
title_fontsize='12',
fontsize=10,
facecolor='white',
edgecolor='black',
borderpad=1
)
plt.tight_layout()
plt.show()
Matplotlib的圖例系統提供了豐富的自定義選項,掌握這些技巧可以顯著提升可視化效果。關鍵點包括:
1. 使用loc
和bbox_to_anchor
精確定位
2. 通過樣式參數美化圖例外觀
3. 處理常見的圖例顯示問題
4. 靈活運用高級功能實現復雜需求
通過實踐這些方法,您可以創建既美觀又專業的圖表圖例。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。