r - How can I put a transformed scale on the right side of a ggplot2? -
i'm creating graph showing change in lake levels on time. i've attached simple example below. add scale (tick marks , annotation) on right side of plot shows elevation in feet. know ggplot2 won't allow 2 different scales (see plot 2 y axes, 1 y axis on left, , y axis on right), because transformation of same scale, there way this? i'd prefer keep using ggplot2 , not have revert plot() function.
library(ggplot2) lakelevels<-data.frame(day=c(1:365),elevation=sin(seq(0,2*pi,2*pi/364))*10+100) p <- ggplot(data=lakelevels) + geom_line(aes(x=day,y=elevation)) + scale_y_continuous(name="elevation (m)",limits=c(75,125)) p
you should have @ link http://rpubs.com/kohske/dual_axis_in_ggplot2.
i've adapted code provided there example. fix seems "hacky", gets part of way there. piece left figuring out how add text right axis of graph.
library(ggplot2) library(gtable) library(grid) lakelevels<-data.frame(day=c(1:365),elevation=sin(seq(0,2*pi,2*pi/364))*10+100) p1 <- ggplot(data=lakelevels) + geom_line(aes(x=day,y=elevation)) + scale_y_continuous(name="elevation (m)",limits=c(75,125)) p2<-ggplot(data=lakelevels)+geom_line(aes(x=day, y=elevation))+ scale_y_continuous(name="elevation (ft)", limits=c(75,125), breaks=c(80,90,100,110,120), labels=c("262", "295", "328", "361", "394")) #extract gtable g1<-ggplot_gtable(ggplot_build(p1)) g2<-ggplot_gtable(ggplot_build(p2)) #overlap panel of 2nd plot on of 1st plot pp<-c(subset(g1$layout, name=="panel", se=t:r)) g<-gtable_add_grob(g1, g2$grobs[[which(g2$layout$name=="panel")]], pp$t, pp$l, pp$b, pp$l) ia <- which(g2$layout$name == "axis-l") ga <- g2$grobs[[ia]] ax <- ga$children[[2]] ax$widths <- rev(ax$widths) ax$grobs <- rev(ax$grobs) ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm") g <- gtable_add_cols(g, g2$widths[g2$layout[ia, ]$l], length(g$widths) - 1) g <- gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b) # draw grid.draw(g)
Comments
Post a Comment