Modifying the Patch in the legend leaving alone the Patch in the scatter plot

Question:

I can change the opacity of an item in the legend of a scatter plot

import matplotlib.pyplot as plt

# note the alpha value            vvvvvvvvvv
plt.scatter(range(10), range(10), alpha=0.15, label='Mount Resegone')
plt.scatter(range(10), [0]*10,    alpha=0.15, label='Rimini Beach')
plt.gca().get_legend_handles_labels()[0][0].set_alpha(1.0)
plt.legend()
plt.show()

but doing that I change also the opacity of every dot in the scatter plot.

I guess that there is a single instance of the Patch, correct me if I’m wrong, but my issue is changing the Patch in the legend leaving alone the Patch in the scatter plot.

enter image description here


Addendum


The solution originally suggested (handle._legmarker.set_alpha(1)) does not work in recent Matplotlib, raising an AttributeError

'PathCollection' object has no attribute '_legmarker'

Fortunately it’s even easier to have the expected behaviour

plt.scatter(range(10), range(10), alpha=0.15, label='Mount Resegone')
plt.scatter(range(10), [0]*10, alpha=0.15, label='Rimini Beach')
plt.legend().legendHandles[0].set_alpha(1.0)

enter image description here

Asked By: gboffi

||

Answers:

Edit: You can just do:

leg = plt.legend()
leg.legendHandles[0].set_alpha(1)

Taken from: Set legend symbol opacity

UPDATED: There is an easier way! First, assign your legend to a variable when you >create it:

leg = plt.legend()

Then:

for lh in leg.legendHandles: 
   lh.set_alpha(1)

OR if the above doesn’t work (you may be using an older version of matplotlib):

for lh in leg.legendHandles: 
   lh._legmarker.set_alpha(1)

to make your markers opaque for a plt.plot or a plt.scatter, respectively.

Note that using simply lh.set_alpha(1) on a plt.plot will make the lines in your legend opaque rather than the markers. You should be able to adapt these two possibilities for the other plot types.

Answered By: Nixcc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.