由来
近日用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')
即可