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

相关推荐
kcuwu.14 小时前
Matplotlib 数据可视化指南:从入门到实战
信息可视化·matplotlib
代码小书生1 天前
Matplotlib,Python 数据可视化核心库!
python·信息可视化·matplotlib
绛橘色的日落(。・∀・)ノ2 天前
Matplotlib第六章场景案例显神通
matplotlib
蜡笔小新..2 天前
Linux下Matplotlib使用Times New Roman字体的解决方案
linux·运维·matplotlib
李昊哲小课3 天前
Pandas数据分析 - 第十一章:数据可视化
信息可视化·数据挖掘·数据分析·pandas·matplotlib
绛橘色的日落(。・∀・)ノ3 天前
Matplotlib 第五章 样式色彩秀芳华
matplotlib
书到用时方恨少!3 天前
Python Matplotlib 使用指南:数据可视化的画笔
python·信息可视化·matplotlib
人工干智能5 天前
科普:%%matplotlib inline:魔法命令 (Cell Magic)
python·matplotlib
绛橘色的日落(。・∀・)ノ6 天前
Matplotlib 第四章 文字图例尽眉目
matplotlib
喝凉白开都长肉的大胖子7 天前
在 Matplotlib 中fontweight一般怎么设置
python·matplotlib