36

I am trying to create a contour plot. I would like to have depth on the Y-axis and time on the X-axis. Right now this is the code that I am using:

par <- ggplot(up_PAR, aes(Time.hour.of.the.day., Depth, z = PAR))
parplot <- par + 
           stat_contour(bins=20, aes(colour=..level..))+ 
           scale_colour_gradient(limits=c(0.000842, 0.00000000195),low="black", high="black") +
           scale_y_reverse()+
           theme_bw()+
           theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
           xlab("Hour of the Day")+
           ylab("Depth(m)")+
           ggtitle("Downwelling PAR (photons/m2/s), January 22nd")
direct.label(parplot)

However, I would like to extend the Depth axis to span from 0-30m. My dataset goes to 175m, but I am only interested in showing the top of the water column.

I know that I can use scale_y_continuous(limit=c(0,30)) but since I've already reversed my axis, and would like to keep it that way, I am unable to also set the limits of the axis.

zx8754
  • 52,746
  • 12
  • 114
  • 209
HAC
  • 391
  • 1
  • 4
  • 5
  • 1
    Why not just filter the `.data` argument? `par <- ggplot(up_PAR[up_PAR$Depth <= 30,], ...)`. – Justin Jul 30 '14 at 19:24
  • 7
    It looks like you can set `limits` inside `scale_y_reverse`. Just make sure you put them in the right (reversed) order - I think `scale_year_reverse(limits = c(30, 0))` will work. – aosmith Jul 30 '14 at 20:57

2 Answers2

64

As @aosmith already pointed out, just use the lim inside the scale_y_reverse

library(ggplot2)
set.seed(15)

ggplot(data.frame(x=sort(runif(20, 0, 20)), y=cumsum(runif(20,0 ,2))), aes(x,y)) +
    geom_point() + 
    scale_y_reverse( lim=c(10,0))

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 3
    you could point out, that the magic is achieved by also putting the limit values in **reversed order**. – loki Nov 16 '18 at 22:06
0

Another option using scale_*_continuous with trans ='reverse' and the limits reversed like this:

library(ggplot2)
set.seed(15)
ggplot(data.frame(x=sort(runif(20, 0, 20)), y=cumsum(runif(20,0 ,2))), aes(x,y)) +
  geom_point() +
  scale_y_continuous(trans = "reverse", limits = c(10, 0))
#> Warning: Removed 10 rows containing missing values (`geom_point()`).

Created on 2022-10-28 with reprex v2.0.2

Data from @MrFlick, thanks!

Quinten
  • 35,235
  • 5
  • 20
  • 53