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

相关推荐
byzh_rc4 天前
[AI工具从入门到入土] 命令行
网络·人工智能·python·深度学习·matplotlib
小何code5 天前
人工智能【第7篇】数据可视化:Matplotlib与Seaborn实战(万字长文+完整代码)
人工智能·机器学习·信息可视化·matplotlib
qq_283720059 天前
Python3 模块精讲:Matplotlib—— 数据可视化、绘图从零基础到实战精通
信息可视化·matplotlib
2401_827499999 天前
数据分析学习06(黑马)-Matplotlib
学习·数据分析·matplotlib
哈伦201914 天前
第六章 Matplotlib案例股票K线图绘制
python·matplotlib
淮北49414 天前
ubuntu22.04将mp4转换成gif
python·scrapy·flask·beautifulsoup·pyqt·matplotlib
xiaotao13119 天前
01-编程基础与数学基石:Matplotlib & Seaborn
人工智能·python·matplotlib
l1t20 天前
uv提供的cpython高版本已经解决了matplotlib无法显示图形问题
matplotlib·uv
哈伦201921 天前
第六章 Matplotlib
matplotlib·anaconda3
l1t21 天前
uv安装的cpython使用matplotlib库作图不能显示的问题起因和解决
matplotlib·uv