Python matplotlib legend for opacity

Example graph

x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 6, 4]
c = [(1, 0, 0, 1),(1, 0, 0, .8),(0, 0, 0, .5),(0, 0, 0, .8),(1, 0, 0, .3)]

plt.scatter(x,y,c=c,s=55)
plt.legend(handles=[mpatches.Patch(color='red',label='Type1'),
                    mpatches.Patch(color='black',label='Type2')])
plt.show()

      

I am drawing a dataset somewhat similar to the one above. In my dataset, the colors represent the classification of the data point, and the opacity represents the magnitude of its error (the dataset is quite dense and makes mistakes allowable.)

I was wondering if it was possible to create some sort of opacity legend, maybe a line of black dots that differ in opacity from 0 to 1, each with a corresponding error.

Thank!

+3


source to share


2 answers


You can add another legend with empty scatter plots as handles where the alpha value of the scatter points changes.

For example, to use 6 different opaque objects ranging from 0 to 1, you can do:



import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 6, 4]
c = [(1, 0, 0, 1),(1, 0, 0, .8),(0, 0, 0, .5),(0, 0, 0, .8),(1, 0, 0, .3)]

plt.scatter(x,y,c=c,s=55)
leg1 = plt.legend(handles=[mpatches.Patch(color='red',label='Type1'),
                    mpatches.Patch(color='black',label='Type2')], loc="upper left")
plt.gca().add_artist(leg1)

error = [0,.2,.4,.6,.8,1]
h = [plt.scatter([],[],s=55, c=(0,0,0,i)) for i in error]
plt.legend(h, error, loc="upper right")

plt.show()

      

enter image description here

+3


source


If using opacity instead of opacity to represent errors is an option, you can use a predefined flower map to display color bars as shown below. Otherwise, I think you can try to define your own flower card.

from matplotlib import pyplot as plt
from matplotlib import patches as mpatches

t1_x = [1, 2, 5]
t1_y = [2, 3, 4]
t1_err = [1, .8, .3]
t2_x = [3, 4]
t2_y = [5, 6]
t2_err = [.5, .8]

plt.figure(figsize=[8, 4])
t1_sc = plt.scatter(t1_x, t1_y, s=55, vmin=0, vmax=1, 
                    c=t1_err, cmap=plt.cm.get_cmap('Reds'))
t2_sc = plt.scatter(t2_x, t2_y, s=55, vmin=0, vmax=1, 
                    c=t2_err, cmap=plt.cm.get_cmap('Greys'))
plt.colorbar(t1_sc)
plt.colorbar(t2_sc)
plt.legend(handles=[mpatches.Patch(color='red',label='Type1'),
                    mpatches.Patch(color='black',label='Type2')])
plt.show()

      



enter image description here

+2


source







All Articles