如何填充绘图中 y 轴附近的区域?

How to fill the area near the y axis in a plot?

我需要绘制数据帧的两个特征,其中 df['DEPTH'] 应该反转并位于 y 轴,而 df['SPECIES'] 应该位于 x 轴。假设该图是一条变线,我想用颜色填充 y 轴附近的区域(线的左侧)。所以我写了一些代码:

df = pd.DataFrame({'DEPTH': [100, 150, 200, 250, 300, 350, 400, 450, 500, 550],
               'SPECIES':[12, 8, 9, 6, 10, 7, 4, 3, 1, 2]})

plt.plot(df['SPECIES'], df['DEPTH'])
plt.fill_between(df['SPECIES'], df['DEPTH'])

plt.ylabel('DEPTH')
plt.xlabel('SPECIES')

plt.ylim(np.max(df['DEPTH']), np.min(df['DEPTH']))

我试过'plt.fill_between',但是绘图的左侧部分没有全部填满。

谁知道填充的部分(蓝色)怎么能到达y轴?

您可以使用 fill_betweenx 而不是 fill_between。它默认从 0 开始填充,因此您需要将 x 限制也设置为 0。

plt.plot(df['SPECIES'], df['DEPTH'])
# changing fill_between to fill_betweenx -- the order also changes
plt.fill_betweenx(df['DEPTH'], df['SPECIES'])

plt.ylabel('DEPTH')
plt.xlabel('SPECIES')

plt.ylim(np.max(df['DEPTH']), np.min(df['DEPTH']))
# setting the lower limit to 0 for the filled area to reach y axis.
plt.xlim(0,np.max(df['SPECIES']))

plt.show()

结果如下。