Matplotlib.pyplot legendplot legend from color dictionary

I am trying to make a legend with my dictionary D_id_color

for my scatter plot. How do 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 a color name, it has the actual color.

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

      

0


source to share


1 answer


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 give:

enter image description here

+3


source







All Articles