I have seen example code here, but seems not work with my case. I am wondering whether anyone could help with plotting secondary axis on two separated y xis without transformation (bar plot). Kindly review the attach data.
Asked
Active
Viewed 41 times
1 Answers
1
We can do it this way:
There are two things to notice:
- First creating the coeff makes problems (NA) because december has NA value therefore the whole graph will not work, just add na.rm=TRUE.
position = position_nudge(x = -.4))
we can avoid that the bars stay on eachother:
coeff <- max(df$Total_test, na.rm = TRUE) / max(df$Total_of_patient, na.rm = TRUE)
df %>%
ggplot(aes(x=fct_inorder(Month), width=.4)) +
geom_col(aes(y=Total_test), fill="green", position = position_nudge(x = -.4)) +
geom_col(aes(y=Total_of_patient*coeff), fill="blue")+
scale_y_continuous(name="Total_test",
sec.axis=sec_axis(~./coeff, name="Total_of_patient")) +
theme(
axis.title.y.left=element_text(color="green"),
axis.text.y.left=element_text(color="green"),
axis.title.y.right=element_text(color="blue"),
axis.text.y.right=element_text(color="blue")
) +
labs(title = "My dual y axis plot", x = element_blank())
data:
structure(list(Month = c("Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Average"), Total_of_patient = c(2001L,
1923L, 1892L, 1674L, 2298L, 2434L, 2397L, 2586L, 1990L, 3027L,
2105L, NA, 2212L), Total_test = c(18308L, 16914L, 17807L, 15514L,
20943L, 21594L, 20365L, 21696L, 15979L, 23627L, 15905L, NA, 18968L
)), class = "data.frame", row.names = c(NA, -13L))

TarJae
- 72,363
- 6
- 19
- 66