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
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值