r - 使用 ggplot 绘制具有两个 y 刻度的图形

标签 r ggplot2 scale

这个问题在这里已经有了答案:





ggplot with 2 y axes on each side and different scales

(17 个回答)


8 个月前关闭。




所以我试图在一个图中编译几个数据框。对于我的 x 值,我有天数,对于 y,我有发生某事的频率。
我的问题是数据帧 (df3) 之一的范围从 0 到 3,其他的范围从 0 到 50。

虚拟数据帧:

day<-c(1,2,3)
b<-c(23,44,22)
c<-c(12,35,49)
d<-c(1,1,3)

df1<-data.frame(day,b)
df2<-data.frame(day,c)
df3<-data.frame(day,d)


ggplot()+ 
  geom_line(data=df1, aes(x=day, y=df1$`b`), color="red") +
  geom_line(data=df2, aes(x=day, y=df2$`c` ), color="green")+
  geom_line(data=df3, aes(x=day, y=df3$`d` ), color="blue")+
  labs(x="Days", y="Number of occurrences")

这工作正常,但我想为 df1 和 df2 创建一个不同的比例,并为 df3 创建另一个。

更新:

我正在尝试这个,但它覆盖了以前的比例:
d<-ggplot()+ 
  geom_line(data=df1, aes(x=day, y=df1$`a`), color="red") +
  geom_line(data=df2, aes(x=day, y=df2$`b` ), color="green")+
  scale_y_continuous(limits=c(0, 50))+
  labs(x="Days", y="Number of occurrences")

d+geom_line(data=df3, aes(x=day, y=df3$`c` ), color="blue")+
  scale_y_continuous(limits=c(0, 3))

最佳答案

我认为您可以使用 sec.axis 来做到这一点。 ggplot2 的参数:

    d<-ggplot()+ 
      geom_line(data=df1, aes(x=day, y=df1$`1`), color="red") +
      geom_line(data=df2, aes(x=day, y=df2$`1` ), color="green")+
      scale_y_continuous(limits=c(0, 50))+
      labs(x="Days", y="Number of occurrences")
    
    d+geom_line(data=df3, aes(x=day, y=df3$`1` ), color="blue")+
      scale_y_continuous(limits=c(0, 3),
           sec.axis = sec_axis(~ . *scale_of_the_new_axis, name = "name of the new axis")
      )
请注意,我在您的代码中添加了这一行:
    sec.axis = sec_axis(~ . *scale_of_the_new_axis, name = "name of the new axis")
编辑:
我对 的数据进行了转换df3 ,然后我应用变换的逆来获得 的真实值df3 反射(reflect)在新轴上。
ggplot()+ 
        geom_line(data=df1, aes(x=day, y=b), color="red") +
        geom_line(data=df2, aes(x=day, y=c ), color="green")+
        geom_line(data=df3, aes(x=day, y=d*50/3), color="blue")+
        scale_y_continuous(limits=c(0, 50), 
                           sec.axis = sec_axis(~ . *3/50, name = "name of the new axis"))+
        labs(x="Days", y="Number of occurrences")
结果是这样的:
enter image description here
让我知道这是否是您想要的。

关于r - 使用 ggplot 绘制具有两个 y 刻度的图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51132115/

相关文章:

r - 从嵌套列表中提取元素到 data.matrix

r - 如何使用 ggplot2 在一行中添加多个线条样式?

r - ggplot2:添加线和点显示手段(stat_summary)

d3.js - d3 js如何从x位置检索时间

Matlab:如何在等高线图上设置对数刻度

html - 转换 : scale while having scaling child element 卡顿

r - 将多个 plotly 图下载到 PDF Shiny

r - 设置 na dplyr 环境中以特定字符串开头的所有值 is.na()、na_if()、startsWith()、regex

r - 在图片的特定区域绘制点

r - 使用 ggplot 创建以零为中心的堆积条形图