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

相关推荐
智航GIS10 天前
11.2 Matplotlib 数据可视化教程
python·信息可视化·matplotlib
weixin_4657909112 天前
热电联产系统智能经济调度:深度强化学习的奇妙应用
matplotlib
我不爱机器学习13 天前
matplotlib如何保存单独的colorbar
matplotlib
爱喝可乐的老王16 天前
数据分析实践--数据解析购房关键
信息可视化·数据分析·pandas·matplotlib
海棠AI实验室17 天前
第 十五 章 可视化入门:Matplotlib 做出像样的图
matplotlib
渡我白衣22 天前
计算机组成原理(11):加法器
python·机器学习·numpy·pandas·matplotlib·计组·数电
老歌老听老掉牙23 天前
使用 Matplotlib 自定义坐标轴字体及刻度样式详解
python·matplotlib
AC赳赳老秦24 天前
DeepSeek教育科技应用:智能生成个性化学习规划与知识点拆解教程
前端·网络·数据库·人工智能·学习·matplotlib·deepseek
AC赳赳老秦1 个月前
行业数据 benchmark 对比:DeepSeek上传数据生成竞品差距分析报告
开发语言·网络·人工智能·python·matplotlib·涛思数据·deepseek
2401_841495641 个月前
【Python高级编程】图着色动态可视化 APP
python·算法·matplotlib·tkinter·回溯法·图着色算法·动态可视化工具