Python中matplotlib-legend图例水平排列

在matplotlib中,图例是用来标识不同数据系列或不同类别的标记和颜色的标签。有时候我们希望将图例水平排列,以节省空间并使得图例更加美观。本文将介绍如何在matplotlib中实现图例的水平排列。

方法一:使用legend的loc参数

我们可以通过legend函数的loc参数来指定图例的位置,其中loc的取值可以是best、upper right、upper left、lower left、lower right、right、center left、center right、lower center、upper center、center,其中best表示最佳位置。

python 复制代码
import matplotlib.pyplot as plt
plt.figure()
# 创建示例数据
x = [1, 2, 3, 4, 5]
y1 = [1, 2, 3, 4, 5]
y2 = [5, 4, 3, 2, 1]

# 绘制图形
plt.plot(x, y1, label='Line 1')
plt.plot(x, y2, label='Line 2')

# 将图例水平排列
plt.legend(loc='center', bbox_to_anchor=(0.5, -0.15), ncol=2)

plt.show()

在这个示例中,我们使用loc='center'将图例放在图的中心位置,并通过bbox_to_anchor=(0.5, -0.15)和ncol=2参数使得图例水平排列,且一行显示两个标签。

See https://geek-docs.com/matplotlib/matplotlib-ask-answer/matplotlib-legend-horizontal_z1.html

相关推荐
留白_2 天前
Matplotlib绘图
信息可视化·数据分析·matplotlib
MATLAB代码顾问3 天前
Python Matplotlib数据可视化实战指南
python·信息可视化·matplotlib
星辰徐哥4 天前
Python AI基础:Matplotlib与Seaborn数据可视化
人工智能·python·matplotlib
斐夷所非5 天前
Python Matplotlib | 基础绘图、复杂函数图与三维图
matplotlib
恣艺9 天前
解决 PyCharm 2024.1+ matplotlib 图表显示异常:Plots 工具窗口空白 / tostring_rgb 报错
ide·pycharm·matplotlib
是上好佳佳佳呀10 天前
【数据分析|Day02】Matplotlib 数据可视化笔记
笔记·matplotlib
ice81303318110 天前
【Python】Matplotlib折线图绘制
开发语言·python·matplotlib
北暮城南12 天前
使用 Claude Code 高效实现图像边缘检测:多算法对比与工程实践
python·opencv·numpy·matplotlib·边缘检测·claude code
red2brick13 天前
【使用PyQt6与Matplotlib编写交互式生成一元二次函数图形程序】
matplotlib
DogDaoDao17 天前
OpenCV 踩坑全指南
图像处理·人工智能·python·opencv·计算机视觉·matplotlib·rgb