MonteCarlo
MonteCarlo

Reputation: 587

Plotting a hydrograph-precipitation plot

I have two numpy arrays which I would like to plot:

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

The precipitation array should come from the top as bars. The runoff as line on the bottom part of the plot. Both have to different axis on the left and the right side. It kind of hard to describe that plot so I just add a link of a plot I found searching with google pics.

Universtity of Jena, Hydrograph plot

I could do it with R but I would like to learn it with the matplotlib module and now I am kind of stuck ...

Upvotes: 5

Views: 5227

Answers (3)

Mengfei Mu
Mengfei Mu

Reputation: 37

@Greg Greg's answer is good. However, you usually do not need to invert the y axis and fix the axis labels manually. Just replace the following code in Greg's answer

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

with one-line code:

plt.gca().invert_yaxis()

Upvotes: 0

Greg
Greg

Reputation: 12234

Here is an idea:

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

enter image description here

There are certainly better ways to do this and from @Pierre_GM's answer it looks like there is a ready made way which is probably better.

Upvotes: 4

Pierre GM
Pierre GM

Reputation: 20339

If you don't mind reading code and figure it out yourself: http://hydroclimpy.sourceforge.net/plotlib.flows.html#plotting-hydrographs

Note that scikits.timeseries is no longer supported, and that scikits.hydroclimpy isn't either. Therefore, it's not a key-in-hand solution. Nevertheless, reading the code should give you some ideas.

Upvotes: 1

Related Questions