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

相关推荐
Gyoku Mint11 小时前
机器学习×第二卷:概念下篇——她不再只是模仿,而是开始决定怎么靠近你
人工智能·python·算法·机器学习·pandas·ai编程·matplotlib
搏博2 天前
将图形可视化工具的 Python 脚本打包为 Windows 应用程序
开发语言·windows·python·matplotlib·数据可视化
Code_流苏5 天前
Python趣学篇:交互式词云生成器(jieba + Tkinter + WordCloud等)
python·pillow·matplotlib·tkinter·wordcloud·jieba分词·词云生成器
AndrewHZ7 天前
【图像处理入门】2. Python中OpenCV与Matplotlib的图像操作指南
图像处理·python·opencv·计算机视觉·matplotlib·图像操作
无闻墨客8 天前
数据可视化--使用matplotlib绘制高级图表
python·机器学习·信息可视化·matplotlib·可视化·数据可视化
Echo-J9 天前
数据可视化(第4、5、6次课)
python·信息可视化·matplotlib·数据可视化
ayas1231911 天前
numpy与matplotlib学习——数据可视化入门
学习·numpy·matplotlib
zhangfeng113312 天前
Python 和 matplotlib 保存图像时,确保图像的分辨率和像素符合特定要求(如 64x64),批量保存 不溢出内存
开发语言·python·matplotlib
李昊哲小课15 天前
matplotlib基本绘图
人工智能·数据分析·matplotlib·数据可视化·pyecharts·seaborn
云攀登者-望正茂15 天前
如何在Mac 上使用Python Matplotlib
python·macos·matplotlib