Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set legend symbol opacity with matplotlib?

I'm working on a plot with translucent 'x' markers (20% alpha). How do I make the marker appear at 100% opacity in the legend?

import matplotlib.pyplot as plt plt.plot_date( x = xaxis, y = yaxis, marker = 'x', color=[1, 0, 0, .2], label='Data Series' ) plt.legend(loc=3, mode="expand", numpoints=1, scatterpoints=1 ) 
like image 231
Don Albrecht Avatar asked Oct 11 '12 21:10

Don Albrecht


People also ask

How do I change the opacity in Matplotlib?

Matplotlib allows you to adjust the transparency of a graph plot using the alpha attribute. If you want to make the graph plot more transparent, then you can make alpha less than 1, such as 0.5 or 0.25. If you want to make the graph plot less transparent, then you can make alpha greater than 1.

How do you make a legend smaller in Matplotlib?

To change the default size of legend text, we use rc() method and pass a keyword argument fontsize. To add a title to the plot, we use title() function. To add label at x-axis, we use xlabel() function. To add label at y-axis, we use ylabel() function.

Is PLT show () blocking?

show() and plt. draw() are unnecessary and / or blocking in one way or the other.


2 Answers

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.

Sources: Synthesized from some good advice by DrV about marker sizes. Update was inspired by useful comment from Owen.

like image 191
lhuber Avatar answered Oct 17 '22 01:10

lhuber


Following up on cosmosis's answer, to make the "fake" lines for the legend invisible on the plot, you can use NaNs, and they will still work for generating legend entries:

import numpy as np import matplotlib.pyplot as plt # Plot data with alpha=0.2 plt.plot((0,1), (0,1), marker = 'x', color=[1, 0, 0, .2]) # Plot non-displayed NaN line for legend, leave alpha at default of 1.0 legend_line_1 = plt.plot( np.NaN, np.NaN, marker = 'x', color=[1, 0, 0], label='Data Series' ) plt.legend() 
like image 41
Rafael Dinner Avatar answered Oct 17 '22 02:10

Rafael Dinner