绘制水位线-降水图

Mon*_*rlo 5 python plot numpy matplotlib

我有两个 numpy 数组,我想绘制它们:

runoff = np.array([1,4,5,6,7,8,9]) 
precipitation = np.array([4,5,6,7,3,3,7])
Run Code Online (Sandbox Code Playgroud)

降水阵列应来自顶部,呈条形。径流作为图底部的线。两者的左侧和右侧都有不同的轴。很难描述这个情节,所以我只是添加了一个我用谷歌图片搜索发现的情节的链接。

耶拿大学,水文图

我可以用 R 来做到这一点,但我想用 matplotlib 模块来学习它,现在我有点卡住了......

Gre*_*reg 3

这是一个想法:

import matplotlib.pyplot as plt
import numpy as np

runoff = np.array([1,4,5,6,7,8,9]) 
precipitation = np.array([4,5,6,7,3,3,7])


fig, ax = plt.subplots()

# x axis to plot both runoff and precip. against
x = np.linspace(0, 10, len(runoff))

ax.plot(x, runoff, color="r")

# Create second axes, in order to get the bars from the top you can multiply 
# by -1
ax2 = ax.twinx()
ax2.bar(x, -precipitation, 0.1)

# Now need to fix the axis labels
max_pre = max(precipitation)
y2_ticks = np.linspace(0, max_pre, max_pre+1)
y2_ticklabels = [str(i) for i in y2_ticks]
ax2.set_yticks(-1 * y2_ticks)
ax2.set_yticklabels(y2_ticklabels)

plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

当然有更好的方法可以做到这一点,从@Pierre_GM 的回答来看,似乎有一种现成的方法可能更好。