
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'm plotting a data set somewhat similar to the above one. In my data set, colors represent the classification of data point and opacity represents the magnitude of its error (the data set is rather dense and makes error bars infeasible.)
I was wondering if it was possible to create some kind of opacity legend, maybe a line of black dots that vary in opacity from 0 to 1, each labeled with the associated error.
Thanks!
You can add another legend with empty scatter plots as handles, where the scatter points' alpha value is varied.
For example to use have 6 different opacities 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()

If using lightness instead of opacity to represent errors is an option, you can use pre-defined colormap to show colorbars like below. Otherwise, I think you can try to define your own colormap.
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()

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With