Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib.pyplot scatterplot legend from color dictionary

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
like image 221
O.rka Avatar asked Jul 08 '15 21:07

O.rka


People also ask

How do you add a color to a legend?

We can try to add legend to the scatterplot colored by a variable, by using legend() function in Matplotlib. In legend(), we specify title and handles by extracting legend elements from the plot.


1 Answers

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:

enter image description here

like image 172
Primer Avatar answered Nov 15 '22 03:11

Primer