【问题标题】:How to put multiple symbols with the same label on the same line in the legend? [duplicate]如何在图例的同一行上放置多个具有相同标签的符号? [复制]
【发布时间】:2019-11-08 23:27:07
【问题描述】:

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

我想要一个图例,它在与其标签对应的一行上并排显示每种颜色的 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 次标签。

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

【问题讨论】:

  • 我写了一个 ScatterHandler in this answer 可以做到这一点。请让我知道我们是否可以将其关闭为重复项,或者您是否想了解有关此内容的具体信息。
  • 其实精确的副本是this one

标签: python matplotlib plot legend


【解决方案1】:

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

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()

【讨论】:

  • 谢谢!这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2019-08-10
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-09
  • 2014-11-12
相关资源
最近更新 更多