0

I have data sets containing daily precipitation and discharge data. Now I would like to plot everything in one plot. All data sets are of length 61, so they can share the same x axis. The discharge data should be plotted the "normal" way, meaning that the y axis starts at the bottom and is placed on the left side. The precipitation data should be plotted "from the top", meaning that the y axis is reversed and placed on the right side.

Here is some code for a minimal reproducible example:

precipitation <- runif(61, min=0, max=25)
discharge <- runif(61, min=370, max=2610)

The result should approximately look like this:

enter image description here

Anybody with an idea how to achieve this?

EDIT: thanks pascal for the answer that implies the usage of ggplot2.

I also found a way by myself to do it with Base R, in case it could help anybody in the future:

precipitation <- runif(61, min=0, max=25)
discharge <- runif(61, min=370, max=2610)

# plot with Base R
par(mar = c(5, 5, 3, 5), xpd = TRUE)
plot(precipitation, type= "l", ylim= c(0,80), ylab= "Precipitation [mm/day]", main= "Comparison", 
     xlab= "Day", col= "blue") 
par(new = TRUE)
plot(discharge, type= "l", xaxt = "n", ylim= rev(c(0,5000)), yaxt = "n", ylab = "", xlab = "", col= "red", lty= 2)
axis(side = 4)
mtext("Discharge [m³/s]", side = 4, line = 3)

The ggplot2 way looks a bit fancier of course.

climsaver
  • 341
  • 2
  • 15
  • Hi climdrag. Could you add a MRE? – dario Feb 11 '21 at 12:28
  • Hi dario. I am sorry, but what do you mean with MRE? – climsaver Feb 11 '21 at 14:15
  • [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). But generally, it's really, really not a good idea to have two (non transformed) y axis. [Link to famous answer by H. Wickham](https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales) – dario Feb 11 '21 at 15:15

1 Answers1

1

ggplot2 can be used to make plots with a second, inverted axis. One has to specify sec.axis in scale_y_continuous(). I'm using a transformation ((100-x)*100) for your data and apply it to the axis as well, so that it fits. This can be changed to any numbers.

ggplot() +
geom_line(aes(y=precipitation, x=1:61), col="orange") + 
geom_line(aes(y=100-discharge/100, x=1:61), col="blue") +
scale_y_continuous(name="rain", sec.axis=sec_axis(~(100-.)*100, name= "discharge"))

enter image description here

pascal
  • 1,036
  • 5
  • 15