如何将具有相同标签的多个符号放置在图例中的同一行上?

2024-06-16 14:09:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个散点图,它由点组成,可以是开放的点,也可以是封闭的点,可以是四种不同的颜色。如果点是打开的,它将有一个标签。如果它关闭,它将有另一个标签

我想一个图例,它显示了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次标签

我可以把代码改成只吃一次土豆和西红柿,上面有一个黑色的闭合点或开放点,但如果可能的话,我更喜欢在一行上有四个不同颜色的点


Tags: none颜色pltgreenbluered标签label
1条回答
网友
1楼 · 发布于 2024-06-16 14:09:42

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

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

相关问题 更多 >