Matplotlib multiple fill_between invert?

Viewed 29

To follow up on a previous question (Matplotlib fill_between invert?), I would like to invert the fill_between for multiple regions. The solution proposed for the original question, inverting foreground and background, doesn't work for multiple regions. Some code is below. Any thoughts?

import numpy as np
import matplotlib.pyplot as plt

# Doesn't work: want to invert filled and empty regions
def f1(x): return 32.0 * x + 2.0
def f2(x): return -55.0 * x
def f3(x): return 15.0 * x + 2.0
def f4(x): return -28.0 * x
xRng=[-1, 1]
plt.plot(xRng, [f1(x) for x in xRng], 'b-', alpha=0.5)
plt.plot(xRng, [f2(x) for x in xRng], 'r-', alpha=0.5)
plt.plot(xRng, [f3(x) for x in xRng], 'b-', alpha=0.5)
plt.plot(xRng, [f4(x) for x in xRng], 'r-', alpha=0.5)
plt.fill_between(xRng, [f1(x) for x in xRng], [f2(x) for x in xRng], color='g', alpha=0.1) # Would like the fill inverted
plt.fill_between(xRng, [f3(x) for x in xRng], [f4(x) for x in xRng], color='g', alpha=0.3) # Would like the fill inverted
plt.title('Want to invert filled and empty regions'); plt.show()

How to invert

1 Answers

You can use axvspan to set the background, and then invert the alphas of the regions you want to fill. Here is an example:

x = np.linspace(-1, 1, 100)
y1 = 32.0 * x + 2.0
y2 = -55.0 * x
y3 = 15.0 * x + 2.0
y4 = -28.0 * x

fig, ax = plt.subplots()

ax.plot(x, y1, 'b', alpha=0.5)
ax.plot(x, y2, 'r', alpha=0.5)
ax.plot(x, y3, 'b', alpha=0.5)
ax.plot(x, y4, 'r', alpha=0.5)

ax.axvspan(x.min(), x.max(), color='g', alpha=0.5)

ax.fill_between(x, y1, y2, color='w', alpha=0.5)
ax.fill_between(x, y3, y4, color='w', alpha=1.0)

enter image description here

You can also make the entire axes object green, though you may end up wanting to adjust the color a bit to make it look the way you want:

fig, ax = plt.subplots(subplot_kw={'facecolor': 'g', 'alpha': 0.5})

Also, remove the line with axvspan in this case.

enter image description here

Both options will look similar if you set

ax.set_xlim(x.min(), x.max())
Related