Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
314 views
in Technique[技术] by (71.8m points)

python - Matplotlib ax.fill_between在上方而不是下方填充(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?

(我正在尝试使用ax.fill_between绘制曲线下的面积,但是由于某些奇怪的原因,一条曲线被绘制得很好,而另一条曲线却没有,这是怎么回事?)

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:

(结果:)

错误的情节

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.

(我也尝试过ax.fill_between(x2, y2, 0, alpha=0.3)ax.fill_between(x2, 0, y2, alpha=0.3)但我得到了相同的图。)

  ask by bluesummers translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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,

(举个例子,考虑一个数据集,其中第一个x值与最后一个x值相同,)

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()

在此处输入图片说明

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

(因此很显然,可以先对数据进行排序来解决。)

Eg,

(例如,)

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

在此处输入图片说明


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...