来自颜色字典的 matplotlib.pyplot 散点图图例
Posted
技术标签:
【中文标题】来自颜色字典的 matplotlib.pyplot 散点图图例【英文标题】:matplotlib.pyplot scatterplot legend from color dictionary 【发布时间】:2015-09-27 00:39:19 【问题描述】:我正在尝试用我的 D_id_color
字典为我的散点图创建一个图例。如何根据这些值使用实际颜色创建图例?
#!/usr/bin/python
import matplotlib.pyplot as plt
from matplotlib import colors
D_id_color = 'A': u'orchid', 'B': u'darkcyan', 'C': u'grey', 'D': u'dodgerblue', 'E': u'turquoise', 'F': u'darkviolet'
x_coordinates = [1,2,3,4,5]
y_coordinates = [3,3,3,3,3]
size_map = [50,100,200,400,800]
color_map = [color for color in D_id_color.values()[:len(x_coordinates)]]
plt.scatter(x_coordinates,y_coordinates, s = size_map, c = color_map)
plt.show()
我希望图例看起来像这样,但不是颜色名称,而是实际颜色。
A orchid
C grey
B darkcyan
E turquoise
D dodgerblue
F darkviolet
【问题讨论】:
【参考方案1】:实现此目的的一种方法:
D_id_color = 'A': u'orchid', 'B': u'darkcyan', 'C': u'grey', 'D': u'dodgerblue', 'E': u'turquoise', 'F': u'darkviolet'
x_coordinates = [1,2,3,4,5,6] # Added missing datapoint
y_coordinates = [3,3,3,3,3,3] # Added missing datapoint
size_map = [50,100,200,400,800,1200] # Added missing datapoint
color_map = [color for color in D_id_color.values()[:len(x_coordinates)]]
plt.scatter(x_coordinates,y_coordinates, s = size_map, c = color_map)
# The following two lines generate custom fake lines that will be used as legend entries:
markers = [plt.Line2D([0,0],[0,0],color=color, marker='o', linestyle='') for color in D_id_color.values()]
plt.legend(markers, D_id_color.keys(), numpoints=1)
plt.show()
这将产生:
【讨论】:
它可以工作,但它会并排输出带有两个标记的图例。谢谢!.legend
采用参数numpoints
设置要显示的点数,因此您可以通过将numpoints=1
添加到legend
调用将其设置为1。以上是关于来自颜色字典的 matplotlib.pyplot 散点图图例的主要内容,如果未能解决你的问题,请参考以下文章