2

I have a contour plot for which I would like to use a legend that has a solid white background, so that the legend is readable over the contour lines.

My problem is that when I change the facecolor, nothing happens. I've also tried changing the framealpha, but nothing happens. Here is a toy code, and the resulting figure. How do I change the facecolor of my legend so that the legend is readable over the contours?

import numpy as np
import matplotlib.pyplot as plt

# Create data

delta = 0.025
x = np.arange(-1.0, 1.0, delta)
y = np.arange(-1.0, 1.0, delta)
X, Y = np.meshgrid(x, y)
Z = np.exp(-X**2 - Y**3)

# Plot data

fig, ax = plt.subplots()
CS = ax.contour(X, Y, Z)

# Create legend.
# Code modified from https://github.com/matplotlib/matplotlib/issues/11134

CS_elem,_ = CS.legend_elements()
ax.legend(CS_elem, ['-X**2 - Y**3'], loc='lower left',facecolor="blue", framealpha=1)

enter image description here

john-hen
  • 4,410
  • 2
  • 23
  • 40
astromonerd
  • 907
  • 1
  • 15
  • 32
  • I am using a style file, but the only legend parameters in there are ```legend.fontsize: 12``` and ```legend.frameon: False``` What parameters do I need to set / reset? – astromonerd Jul 17 '19 at 20:19
  • Check the comment of @ImportanceOfBeingErnest underneath my answer. Make sure you are using your code correctly. Restart your terminal and try your code again – Sheldore Jul 17 '19 at 22:38

2 Answers2

4

As per your comment, you have set legend.frameon to False. The default value is True, in order to "draw the legend on a background patch" according to the documentation of the matplotlibrc file. Without the patch, the facecolor cannot be applied.

john-hen
  • 4,410
  • 2
  • 23
  • 40
1

Your code works fine on matplotlib 2.2.2. Nevertheless, you can try the following solution as suggested in this answer.

CS_elem,_ = CS.legend_elements()
leg = ax.legend(CS_elem, ['-X**2 - Y**3'], loc='lower left',
                framealpha=1)
frame = leg.get_frame()
frame.set_facecolor('blue')

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71
  • It also works fine on matplotlib 3.1.0. Possibly OP has modified the style, or in any case has something outside the shown code that prevents this to work. (I'm saying this because if `facecolor` does not work, why should `set_facecolor`?) – ImportanceOfBeingErnest Jul 17 '19 at 21:52