首页 > 解决方案 > 如何在图例的同一行上放置多个具有相同标签的符号?

问题描述

我正在制作一个散点图,它由可以是开点或闭点的点组成,并且可以有四种不同的颜色。如果点是开放的,它将有一个标签。如果它已关闭,它将有另一个标签。

我想要一个图例,它在与其标签对应的一行上并排显示每种颜色的 4 个点,而不是每行 1 个具有相同标签的点。

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(3)
y = np.arange(3)



plt.scatter(x,y, color = 'blue',  label = 'potatoes')
plt.scatter(x,y, color = 'green', label = 'potatoes')
plt.scatter(x,y, color = 'red', label = 'potatoes')
plt.scatter(x,y, color = 'magenta', label = 'potatoes')

plt.scatter(x,y, color = 'blue',  facecolors='none', label = 'tomatoes')
plt.scatter(x,y, color = 'green',  facecolors='none', label = 'tomatoes')
plt.scatter(x,y, color = 'red',  facecolors='none', label = 'tomatoes')
plt.scatter(x,y, color = 'magenta',  facecolors='none', label = 'tomatoes')

plt.plot(x,y, color = 'blue'    , label= "Florida")
plt.plot(x,y, color = 'green'   , label= "California")
plt.plot(x,y, color = 'red'     , label= "Idaho")
plt.plot(x,y, color = 'magenta' , label= "Montana")

l = plt.legend(handlelength = 0)
llines = l.get_texts()
llines[0].set_color('blue')
llines[1].set_color('green')
llines[2].set_color('red')
llines[3].set_color('magenta')

我希望图例输出在一行的标签旁边有四个不同的颜色点,而不是每个颜色点重复 4 次标签。

我可以将代码更改为只有一次带有黑色封闭或开放点的土豆和西红柿,但如果可能的话,我更喜欢在一行中使用四个不同颜色的点。

标签: pythonmatplotlibplotlegend

解决方案


您可以将带有点的元组传递给带有如下点的图例:

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

x = np.arange(3)
y = np.arange(3)

p1 = plt.scatter(x,y, color = 'blue')
p2 = plt.scatter(x,y, color = 'green')
p3 = plt.scatter(x,y, color = 'red')
p4 = plt.scatter(x,y, color = 'magenta')

t1 = plt.scatter(x,y, color = 'blue',  facecolors='none')
t2 = plt.scatter(x,y, color = 'green',  facecolors='none')
t3 = plt.scatter(x,y, color = 'red',  facecolors='none')
t4 = plt.scatter(x,y, color = 'magenta',  facecolors='none')

plt.legend([(p1, p2, p3, p4), (t1, t2, t3, t4)], ['potatoes', 'tomatoes'],
           scatterpoints=1, numpoints=1, handler_map={tuple: HandlerTuple(ndivide=None)})
plt.show()

example_legend


推荐阅读