如何将转换后的比例放在 ggplot2 的右侧? [英] How can I put a transformed scale on the right side of a ggplot2?

查看:18
本文介绍了如何将转换后的比例放在 ggplot2 的右侧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个图表,显示湖泊水位随时间的变化.我在下面附上了一个简单的例子.我想在图的右侧添加一个比例尺(刻度线和注释),以英尺为单位显示高程.我知道 ggplot2 不允许两个不同的比例(见 绘制有 2 个 y 轴,一个 y 轴在左边,另一个 y 轴在右边),但因为这是对同样的规模,有没有办法做到这一点?我更愿意继续使用 ggplot2 而不必恢复到 plot() 函数.

I'm creating a graph showing the change in lake levels over time. I've attached a simple example below. I would like to add a scale (tick marks and annotation) on the right side of the plot that shows the elevation in feet. I know ggplot2 won't allow two different scales (see Plot with 2 y axes, one y axis on the left, and another y axis on the right), but because this is a transformation of the same scale, is there a way to do this? I'd prefer to keep using ggplot2 and not to have to revert to the 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

推荐答案

你应该看看这个链接 http://rpubs.com/kohske/dual_axis_in_ggplot2.

You should have a look at this link http://rpubs.com/kohske/dual_axis_in_ggplot2.

我已经为您的示例修改了那里提供的代码.这个修复看起来非常hacky",但它让你在那里的一部分.剩下的唯一部分是弄清楚如何将文本添加到图形的右轴.

I've adapted the code provided there for your example. This fix seems very "hacky", but it gets you part of the way there. The only piece left is figuring out how to add text to the right axis of the 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 the panel of the 2nd plot on that of the 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 it
   grid.draw(g)

这篇关于如何将转换后的比例放在 ggplot2 的右侧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆