首页 > 解决方案 > 有没有办法在 Matplotlib 中从未接触过的两个垂直函数之间进行遮蔽?

问题描述

我目前正在为一个项目重建温度曲线,该曲线在 y 轴上显示高度,在 x 轴上显示温度波动,如下所示:

具有 +/- 2-sigma 误差范围的温度曲线

在图的中间有一条粗线,表示插值/模拟的温度曲线。插值轮廓的左右两侧是误差界限,基本上是带有 +/- 误差值的实际数据。我想在这些误差范围之间加上阴影,表明插值温度曲线位于这些范围内。

然而,问题是它们从不接触,所以本质上它们具有不同的 x 值。它们也是垂直运行的,因此plt.fill_betweenaxvspan (只生成一个矩形)都不起作用。我尝试颠倒一些参数的顺序,因为我正在垂直绘制它会像这样工作:

plt1.plot(data, altitude, 'b') #Make the first plot show the temperature profile
plt1.plot(maxSigma, rawalt, 'r', linewidth = 0.3)
plt1.plot(minSigma, rawalt, 'g', linewidth = 0.3)
plt1.fill_between(rawalt, minSigma, maxSigma)

但事后看来,这对我来说可能是一个愚蠢的镜头。我难住了。

标签: pythonmatplotlibplotdata-science

解决方案


为了扩展ImportanceOfBeingErnest的评论,这里是一个完整的例子,展示了的用法,matplotlib.pyplot.fill_betweenx

import matplotlib.pyplot as plt
import numpy as np

np.random.seed(0)
fig = plt.figure(figsize=(6,8))

n = 200
x = [0.0]
xa = []
xe = []
# Generate some data with a random, accumulating jitter
for i in range(n-1):
    x.append((np.random.random()-0.5)+x[i-1])
ma = 10
# Add some variable error on each side of the generated data
# and use a running average to smooth the generated data
for i in range(n-ma):
    xa.append(sum(x[i:i+ma])/float(ma))
    xe.append([xa[i]-2+(np.random.random()-0.5)*0.25,xa[i]+2+(np.random.random()-0.5)*0.25])

y = np.linspace(10,0,n-ma)
xe = np.array(xe)
plt.plot(xa, y, lw=0.75)
plt.fill_betweenx(y, xe[:,0], xe[:,1], alpha=0.4)
plt.show()

在此处输入图像描述


推荐阅读