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

相关推荐
MediaTea5 小时前
Python 第三方库:matplotlib(科学绘图与数据可视化)
开发语言·python·信息可视化·matplotlib
Kratzdisteln6 小时前
【Python】绘制椭圆眼睛跟随鼠标交互算法配图详解
python·数学·numpy·pillow·matplotlib·仿射变换
万粉变现经纪人14 小时前
如何解决 pip install -r requirements.txt 子目录可编辑安装缺少 pyproject.toml 问题
开发语言·python·scrapy·beautifulsoup·scikit-learn·matplotlib·pip
jie*6 天前
小杰深度学习(seventeen)——视觉-经典神经网络——MObileNetV3
人工智能·python·深度学习·神经网络·numpy·matplotlib
jie*6 天前
小杰深度学习(sixteen)——视觉-经典神经网络——MobileNetV2
人工智能·python·深度学习·神经网络·tensorflow·numpy·matplotlib
~~李木子~~8 天前
用 Matplotlib 实现数据可视化3 个案例实战
信息可视化·matplotlib
OG one.Z9 天前
08_Matplotlib数据可视化
信息可视化·matplotlib
eqwaak011 天前
动态图表导出与视频生成:精通Matplotlib Animation与FFmpeg
开发语言·python·ffmpeg·音视频·matplotlib
MoRanzhi120311 天前
15. Pandas 综合实战案例(零售数据分析)
数据结构·python·数据挖掘·数据分析·pandas·matplotlib·零售
Love__Tay12 天前
【数据分析与可视化】2025年一季度金融业主要行业资产、负债、权益结构与增速对比
金融·excel·pandas·matplotlib