How can I plot with 2 different y-axes in R with ggplot2?

I have the next Data

      Fecha    cases  deaths countries     pop2018 TotalCases  TCP
1   2020-03-29  2546    260 United_Kingdom  66488991    17089   NA
2   2020-03-30  2433    209 United_Kingdom  66488991    19522   0.14237229
3   2020-03-31  2619    180 United_Kingdom  66488991    22141   0.13415634
4   2020-04-01  3009    381 United_Kingdom  66488991    25150   0.13590172
5   2020-04-02  4324    743 United_Kingdom  66488991    29474   0.17192843
6   2020-04-03  4244    389 United_Kingdom  66488991    33718   0.14399131
7   2020-04-04  4450    684 United_Kingdom  66488991    38168   0.13197699
8   2020-04-05  3735    708 United_Kingdom  66488991    41903   0.09785684

And the next plots

ggplot(data=Data_UK7, aes(x=Fecha, y=TCP)) +
  geom_line(linetype = "twodash")+
  geom_point()+
  scale_x_date(date_breaks ="1 day")+
  scale_y_continuous(breaks = seq(0,1,0.01))

enter image description here

ggplot(Data_UK7)+
  geom_col(aes(x=Fecha,y=TotalCases))+
  scale_x_date(date_breaks ="1 day")

enter image description here

It's possible to make a plot with this 2 graphs together ? Something like this: enter image description here

Upvotes: 0

Views: 94

Answers (1)

bs93
bs93

Reputation: 1316

"All secondary axes must be based on a one-to-one transformation of the primary axes" per the ggplot2 docs for adding secondary y-axis via scale_y_continuous.

The TotalCases scale is about 200000 times (value around 40000) larger than the TCP scale (value around 0.15). You can play around with this number to get precise positioning, but something like this could work:

Data_UK7 <- read.table(text = 
                     "      Fecha    cases  deaths countries     pop2018 TotalCases  TCP
1   2020-03-29  2546    260 United_Kingdom  66488991    17089   NA
2   2020-03-30  2433    209 United_Kingdom  66488991    19522   0.14237229
3   2020-03-31  2619    180 United_Kingdom  66488991    22141   0.13415634
4   2020-04-01  3009    381 United_Kingdom  66488991    25150   0.13590172
5   2020-04-02  4324    743 United_Kingdom  66488991    29474   0.17192843
6   2020-04-03  4244    389 United_Kingdom  66488991    33718   0.14399131
7   2020-04-04  4450    684 United_Kingdom  66488991    38168   0.13197699
8   2020-04-05  3735    708 United_Kingdom  66488991    41903   0.09785684
                   ",
                   header=TRUE)
Data_UK7$Fecha <- as.Date(Data_UK7$Fecha)
 ggplot(Data_UK7)+
    geom_col(aes(x=Fecha,y=TotalCases))+
    scale_x_date(date_breaks ="1 day")+
    geom_line(aes(x=Fecha, y=TCP*200000),linetype = "twodash")+
    geom_point(aes(x=Fecha, y=TCP*200000))+
    theme_classic()+
    scale_y_continuous(sec.axis = sec_axis(~./200000, name = "TCP"))

The scaling needs to happen in both the specific geoms that will go on secondary axis (for this example the geom_point and geom_line with TCP in the aes) and also in scale_y_continuous.

enter image description here

Upvotes: 2

Related Questions