matplotlib.pyplot scatterplot legend from color di

2019-01-26 02:16发布

问题:

I'm trying to make a legend with my D_id_color dictionary for my scatterplot. How can I create a legend based on these values with the actual 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()

I want the legend to look like this but instead of color name, it would have the actual color.

A orchid
C grey
B darkcyan
E turquoise
D dodgerblue
F darkviolet

回答1:

One way to achieve this:

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

This will yield: