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 )
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.
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.
show() and plt. draw() are unnecessary and / or blocking in one way or the other.
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.
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()
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