How to use matplotlib fill_between for default ylim

Viewed 342

Without Fill :

enter image description here

With Fill :

enter image description here

plt.fill_between(n,data)

I want to fill for default y limit.

Also can I do a gradient fill?

1 Answers

You can use ax.get_ylim() to get the y limits. ax.fill_between(n, ymin, data) fills the area between the minimum and the curve. If you don't supply two y-values for fill_between, 0 is used as default, which in this case is very far away from the actual curve.

The polygon created by fill_between can be extracted and used as a clipping path for a gradient rectangle.

Here is some example code:

import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch
import numpy as np

np.random.seed(123)
n = np.arange(12)
data = np.random.randint(97800, 98400, len(n))
fig, ax = plt.subplots()
ax.plot(n, data, color='dodgerblue')
ymin, ymax = ax.get_ylim()
fill_poly = ax.fill_between(n, ymin, data, color='none')
gradient_rect = ax.imshow(np.arange(256).reshape(-1, 1), extent=[n.min(), n.max(), ymin, ymax],
                      cmap='Blues_r', aspect='auto')
clip_poly = PathPatch(fill_poly.get_paths()[0], transform=ax.transData)
gradient_rect.set_clip_path(clip_poly)
plt.show()

fill between with gradient

Related