YouTube video link with explanations for these examples Video link
Video link https://youtu.be/e9IcAEaxDB4
Here is a link for subscribing to this YouTube channel. https://www.youtube.com/c/TechAnswers88?s_confirmation=1
How to create a secondary axis in a ggplot chart.
library(ggplot2)
library(dplyr)
# Create the sample data
df <- data.frame(date = seq(as.Date('2021-01-01')
, as.Date('2021-01-31')
, by = "day")
, patients = as.integer(runif(31
,min = 1000
, max = 1200
))
, deaths = as.integer(runif(31
,min = 100
, max = 120
))
)
df
## date patients deaths
## 1 2021-01-01 1086 117
## 2 2021-01-02 1040 102
## 3 2021-01-03 1028 116
## 4 2021-01-04 1108 100
## 5 2021-01-05 1014 100
## 6 2021-01-06 1071 117
## 7 2021-01-07 1004 104
## 8 2021-01-08 1036 118
## 9 2021-01-09 1127 101
## 10 2021-01-10 1053 113
## 11 2021-01-11 1027 113
## 12 2021-01-12 1047 100
## 13 2021-01-13 1197 110
## 14 2021-01-14 1182 116
## 15 2021-01-15 1116 114
## 16 2021-01-16 1141 101
## 17 2021-01-17 1118 104
## 18 2021-01-18 1019 102
## 19 2021-01-19 1027 111
## 20 2021-01-20 1003 118
## 21 2021-01-21 1158 104
## 22 2021-01-22 1158 116
## 23 2021-01-23 1064 102
## 24 2021-01-24 1052 108
## 25 2021-01-25 1140 114
## 26 2021-01-26 1151 101
## 27 2021-01-27 1069 119
## 28 2021-01-28 1000 102
## 29 2021-01-29 1138 102
## 30 2021-01-30 1185 111
## 31 2021-01-31 1000 109
See that we have used custom breaks on the secondary axis on the right hand side.
pl <- ggplot(data = df, aes(x = date))
pl <- pl + geom_line(aes(y = patients), color = "blue")
pl <- pl + geom_line(aes(y = deaths), color = "red")
pl <- pl + theme_minimal()
pl <- pl + scale_y_continuous(name = "Patients"
, sec.axis = sec_axis(trans = ~./10
, breaks = c(5,10,15,20)
, name = "Deaths"))
pl <- pl + theme(axis.title.y = element_text(color = "blue")
, axis.text.y = element_text(color = "blue")
,axis.title.y.right = element_text(color = "red")
, axis.text.y.right = element_text(color = "red")
)
pl <- pl + labs(x = "Date"
, y = "No. of Patients"
, title = "Daily patient count and deaths")
pl
pl <- ggplot(data = df, aes(x = date))
pl <- pl + geom_line(aes(y = patients), color = "blue")
pl <- pl + geom_col(aes(y = deaths), fill = "red")
pl <- pl + theme_classic()
pl <- pl + scale_y_continuous(name = "Patients"
, sec.axis = sec_axis(trans = ~./10
, name = "Deaths"))
pl <- pl + theme(axis.title.y = element_text(color = "blue"),
axis.title.y.right = element_text(color = "red")
)
pl
Here is the link to subscribe to this channel.