【发布时间】: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 次标签。
我可以将代码更改为只使用一次带有黑色闭合或开放点的土豆和西红柿,但如果可能的话,我更喜欢在一行中使用四个不同颜色的点。
【问题讨论】:
-
我写了一个
ScatterHandlerin this answer 可以做到这一点。请让我知道我们是否可以将其关闭为重复项,或者您是否想了解有关此内容的具体信息。 -
其实精确的副本是this one。
标签: python matplotlib plot legend