您好,登录后才能下订单哦!
# 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。