bluesummers
bluesummers

Reputation: 12627

Matplotlib ax.fill_between fills above, instead of below

I am trying to use ax.fill_between to plot the area under a curve, but for some odd reason, one curve gets plotted just fine, and the other one isn't, what goes wrong?

Code:

_, ax = plt.subplots(figsize=(9, 7))

sns.lineplot(x1, y1)
ax.fill_between(x1, y1, alpha=0.3)
sns.lineplot(x2, y2)
ax.fill_between(x2, y2, alpha=0.3)

Result:

Errored plot

I've tried also ax.fill_between(x2, y2, 0, alpha=0.3) and ax.fill_between(x2, 0, y2, alpha=0.3) but I get the same plot.

Upvotes: 0

Views: 159

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339430

Something like this can happen if the data isn't sorted. To give an example, consider a dataset where the very first x value is identical to the last,

import numpy as np; np.random.seed(346)
import matplotlib.pyplot as plt

x = np.linspace(0, 50, 51)
x[0] = x[-1]
y = np.cumsum(np.random.randn(51))+6


fig, ax = plt.subplots()
ax.plot(x,y)
ax.fill_between(x,y, alpha=0.3)

plt.show()

enter image description here

So obviously it can be solved by sorting the data first. E.g.,

ind = np.argsort(x)
x=x[ind]
y=y[ind]

enter image description here

Upvotes: 2

Related Questions