5

I like to plot simple time series data and overplot precipitation data. The following code plots a line for the usual data and adds barplots (or histogram bars) for the precipitation data.

D # a simple (zoo) time series
P # a simple (zoo) time series of precipitation
plot(D, type="l")
lines(P, type="h", lwd=5)

But the bars are based on the y=0 axis and rise topwards. But usual in hydrology are precipitation bars that are based on the very top axis and "flow" downwards. D has arbitrary y-ranges, so I would prefer a solution that does fix a value for the baseline of P.

I googled a lot but did not manage to find how to do this in R without ggplot and without extra packages like hydrograph.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Martin
  • 1,395
  • 1
  • 11
  • 33

2 Answers2

3

Not sure whether I understood it correctly so this is my interpretation. Don't know whether this works with zoo objects as well.

# Create some mock data
x<-runif(20,0,100)
y<-runif(20,0,100)

# This is the normal topwards plot
plot(x,y,type="h")

enter image description here

# And this is the downwards plot
plot(x, y, ylim = rev(range(y)),type="h") 

enter image description here

horseoftheyear
  • 917
  • 11
  • 23
  • I need this to overlay a previous plot, aligned to its top. Would be great to have your y-axis on the right top of the plot. – Martin Apr 09 '14 at 20:51
  • If you want to have the y-axis on the right use `axes=FALSE` in `plot` and specify the axes separately. SO for y-axis on the right top you would use `axis(4,ylim = rev(range(y)))` and `mtext("y",side=4)`for the label. – horseoftheyear Apr 09 '14 at 21:04
2

With the help of BlankUsername I found the following solution for zoo time series. I have not been aware of something like par(new=T) or the axis() command before:

# plot the usual data
plot(D)
# add half day to indicate that P is a sum of the whole day
index(P) <- index(P) + 0.5
# define an overlay plot without border
par(bty="n", new=T)
plot(P, type="h", ylim=rev(range(P)), # downward bars by BlankUsername
    yaxt="n", xaxt="n", ann=F, # do not plot x and y axis
    xlim=c(start(D),end(D)), # without xlim the two overlayed plots will not fit
    lwd=10, col=rgb(0,0,0,0.1) ) # suggested cosmetics
# add right axis (4) to describe P
axis(4, pretty(range(P)), col.axis="grey", col="grey", las=1, cex.axis=0.7 )
# reset border and overlay
par(bty="o", new=F)
Martin
  • 1,395
  • 1
  • 11
  • 33