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

相关推荐
L Jiawen21 小时前
【Python 2D绘图】Matplotlib绘图(统计图表)
开发语言·python·matplotlib
SomeB1oody2 天前
【Python机器学习】1.10. 逻辑回归实战(高阶):超多阶(大于2)的逻辑回归
人工智能·python·机器学习·逻辑回归·matplotlib
伪编辑科学家3 天前
[数据可视化的python脚本实现]关于餐厅消费的不同维度分析
python·信息可视化·pandas·matplotlib
蹦蹦跳跳真可爱5894 天前
Python----数据分析(Matplotlib四:Figure的用法,创建Figure对象,常用的Figure对象的方法)
python·数据分析·matplotlib
蹦蹦跳跳真可爱5895 天前
Python----数据分析(Matplotlib五:pyplot的其他函数,Figure的其他函数, GridSpec)
python·数据分析·matplotlib
終不似少年遊*6 天前
综合使用pandas、numpy、matplotlib、seaborn库做数据分析、挖掘、可视化项目
开发语言·python·机器学习·numpy·pandas·matplotlib·seaborn
蹦蹦跳跳真可爱5897 天前
Python----数据分析(Matplotlib三:绘图二:箱图,散点图,饼图,热力图,3D图)
python·数据分析·matplotlib
大数据张老师8 天前
Python数据可视化——Matplotlib的基本概念和使用
python·信息可视化·matplotlib
web150854159358 天前
基于python的网络爬虫爬取天气数据及可视化分析(Matplotlib、sk-learn等,包括ppt,视频)
爬虫·python·matplotlib
dundunmm10 天前
【数据挖掘】Matplotlib
人工智能·python·数据挖掘·matplotlib