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

相关推荐
满怀10152 天前
【Python进阶】数据可视化:Matplotlib从入门到实战
python·信息可视化·数据分析·matplotlib·数据可视化
是一只努力的小菜鸡啦3 天前
Matplotlib的应用
matplotlib
失去妙妙屋的米奇8 天前
matplotlib数据展示
开发语言·图像处理·python·计算机视觉·matplotlib
小旺不正经10 天前
人工智能基础-matplotlib基础
人工智能·matplotlib
Thanks_ks10 天前
利用 Python 进行股票数据可视化分析
python·matplotlib·热力图·seaborn·可视化分析·股票数据·yfinance
拾荒的小海螺13 天前
【数据分析实战】使用 Matplotlib 绘制折线图
信息可视化·数据分析·matplotlib
灵均66614 天前
机器学习-线性回归模型
人工智能·机器学习·线性回归·numpy·pandas·scikit-learn·matplotlib
懒羊羊不进村15 天前
Python基础——Matplotlib库
开发语言·python·matplotlib
月小水长18 天前
Django 使用 matplotlib 遇到 RuntimeError: main thread is not in main loop 解决办法
python·django·matplotlib·thread·anr
搬砖的阿wei19 天前
Matplotlib:数据可视化的艺术与科学
python·信息可视化·matplotlib