Plot with ggplot a graph with two y scales

2020-06-22 15:37发布

问题:

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.

Dummy dataframes:

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

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

UPDATE:

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

回答1:

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

EDIT:

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

The result is this:

Let me know if this is what you want.



标签: r ggplot2 scale