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

相关推荐
PacosonSWJTU21 小时前
python使用matplotlib画图
开发语言·python·matplotlib
Caron_xcb2 天前
大数据——解决Matplotlib 字体不足问题(Linux\mac\windows)
大数据·linux·matplotlib
迷人的小荔枝5 天前
seaborn
matplotlib
玫瑰花店7 天前
ubuntu中解决matplotlib无法显示中文问题
linux·ubuntu·matplotlib
龙虎榜小红牛系统13 天前
Python项目源码63:病历管理系统1.0(tkinter+sqlite3+matplotlib)
python·sqlite·matplotlib
大熊背15 天前
如何解决matlab/octave画图legend图例颜色一样的问题?
matlab·legend
eqwaak017 天前
Matplotlib高阶技术全景解析(续):动态交互、三维可视化与性能优化
开发语言·python·语言模型·性能优化·交互·matplotlib
T0uken17 天前
【Python】Matplotlib:立体永生花绘制
开发语言·python·matplotlib
captain_keating19 天前
使用matplotlib绘制Raincloud图/云雨图/柱状图/小提琴图
python·matplotlib
YiSLWLL20 天前
使用Tauri 2.3.1+Leptos 0.7.8开发桌面小程序汇总
python·rust·sqlite·matplotlib·visual studio code