用ggplot绘制具有两个y比例的图形 [英] Plot with ggplot a graph with two y scales

查看:89
本文介绍了用ggplot绘制具有两个y比例的图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I am trying to compile several dataframe in one graph. For my x value I have the number of days, and for y I have the frequency of something happening. My problem is that one of the dataframe (df3) ranges from 0 to 3, and the others from 0 to 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创建另一个比例.

This works fine, but I want to creat a diferent scale for df1 and df2, and another to df3.

更新:

我正在尝试此操作,但它会覆盖以前的比例:

I am trying this, but it overwrites the previous scale:

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))

推荐答案

我认为您可以使用ggplot2sec.axis参数来实现:

I think you can do it using the sec.axis param of 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")
  )

请注意,我在您的代码上添加了这一行:

Note that I added this line on your code:

sec.axis = sec_axis(~ . *scale_of_the_new_axis, name = "name of the new axis")

我对 df3 的数据进行了变换,然后应用了逆变换以使 df3 的实际值反映在新轴上.

I applied a transformation to the data of df3, then I applied the inverse of the transformation to have the real values of df3 reflected on the new axis.

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")

结果是这样的:

让我知道这是否是您想要的.

Let me know if this is what you want.

这篇关于用ggplot绘制具有两个y比例的图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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