Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python matplotlib legend for opacity

Example Plot

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!

like image 601
Matthew Avatar asked Feb 26 '26 01:02

Matthew


2 Answers

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

enter image description here

like image 181
ImportanceOfBeingErnest Avatar answered Feb 28 '26 13:02

ImportanceOfBeingErnest


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

enter image description here

like image 25
Y. Luo Avatar answered Feb 28 '26 13:02

Y. Luo



Donate For Us

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