I want to plot a bar graph together with a line graph (secondary axis). The observation values for the line graph appears but the line doesnt appear as shown in diagram. I think maybe my transformation is wrong? Below are my code.
Year <- c( "2017", "2018","2019","2020")
Response <- c(6, 10, 6, 2)
Rate <- c(0.22, 0.36, 0.21, 0.07)
df <- data.frame(month, Response,Rate)
#Chart
library(ggplot2)
ggplot(df) +
geom_bar(aes(x=Year, y=Response),stat="identity", fill="yellow",colour="sienna3")+
geom_text(aes(label=Response, x=Year, y=1.09*Response),colour="black")+
geom_line(aes(x=Year, y=Rate*20),colour="black",stat="identity")+
geom_text(aes(label=Rate, x=Year, y=Rate*25), colour="black")+
scale_y_continuous("# Cases") +
xlab("Month") +
theme(axis.text = element_text(size = 13)) +
theme(axis.title = element_text(size = 14)) +
scale_y_continuous(sec.axis = sec_axis(~./25, name="Incidence rate/100000"))
I tried to clean up a bit your code to solve your problem and give you out a couple of ideas on how to improve your code.
Year <- c(2017, 2018, 2019, 2020)
Response <- c(6, 10, 6, 2)
Rate <- c(0.22, 0.36, 0.21, 0.07)
df <- data.frame(Year, Response, Rate)
library(ggplot2)
correction <- 20
ggplot(df, aes(x = Year)) +
geom_bar (aes(y = Response),
stat = "identity", fill = "yellow", colour = "sienna3", alpha = 0.6)+
geom_text(aes(y = Response, label = Response),
colour = "black", vjust = -0.5)+
geom_line(aes(y = Rate * correction),
colour = "black", size = 1)+
geom_text(aes(y = Rate * correction, label = Rate * correction),
colour = "black", vjust = -1)+
ylab("# Cases") +
xlab("Year") +
theme(axis.text = element_text(size = 13)) +
theme(axis.title = element_text(size = 14)) +
scale_y_continuous(sec.axis = sec_axis(~./correction,
name = "Incidence rate/100'000")) +
theme_minimal()
Notice:
Year
is now numericalMonth
and Year
vjust
alpha
parameter to ease up to my eyes that strong yellow :-)stat = "identity"
from geom_line
correction
to have that correction factor of yours always equal among all the transformationstheme
to make it look a bit more cleanYou should add a title. Use ggtitle