栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

matplotlib合并多个Legend为一个

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

matplotlib合并多个Legend为一个

由来

近日用Python的matplotlib库画曲线的时候,遇到一个需要将多个legend合并为一个显示的问题。
比如最简单的代码

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
y2 = [1, 5, 91, 116]
y3 = [1, 24, 29, 216]
y4 = [12, 224, 229, 216]

plt.plot(x, y, marker='.', label='label1')
plt.plot(x, y2, marker='.', label='label2')
plt.plot(x, y3, marker='.', label='label3')
plt.plot(x, y4, marker='.', label='label4')
plt.legend(loc='best')
plt.show()

得到结果为

但我的情况是,y,y2,y3,y4都是某一个变量情况下的输出时,我想把它们合并显示为xxx,研究了一会官网,找到了办法

结果

先看结果,基本是符合我的要求的

直接上代码

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple

x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
y2 = [1, 5, 91, 116]
y3 = [1, 24, 29, 216]
y4 = [12, 224, 229, 216]

fig, ax = plt.subplots()
p1, = ax.plot(x, y, marker='.')
p2, = ax.plot(x, y2, marker='.')
p3, = ax.plot(x, y3, marker='.')
p4, = ax.plot(x, y4, marker='.')
plt.legend(loc='best')
ax.legend([(p1, p2, p3, p4)], ['xxx'],
          numpoints=1,
          handler_map={tuple: HandlerTuple(ndivide=1)})
plt.show()

legend和曲线的颜色不对,统一一下

import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerTuple

x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
y2 = [1, 5, 91, 116]
y3 = [1, 24, 29, 216]
y4 = [12, 224, 229, 216]

fig, ax = plt.subplots()
p1, = ax.plot(x, y, marker='.', markersize=6, color='tab:red')
p2, = ax.plot(x, y2, marker='.', markersize=6, color='tab:red')
p3, = ax.plot(x, y3, marker='.', markersize=6, color='tab:red')
p4, = ax.plot(x, y4, marker='.', markersize=6, color='tab:red')
plt.legend(loc='best')
ax.legend([(p1, p2, p3, p4)], ['xxx'],
          numpoints=1,
          handler_map={tuple: HandlerTuple(ndivide=1)})
# 或者使用更简单的代码
# ax.legend(handles=[p1])         

plt.show()

此时控制台会报一个警告
No handles with labels found to put in legend
只要把代码
p1, = ax.plot(x, y, marker='.', markersize=6, color='tab:red')
修改为
p1, = ax.plot(x, y, marker='.', label='xx',markersize=6, color='tab:red')
即可

参考文献
  1. HandlerTuple
  2. pyplot
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/675090.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号