Combination of line and line graphs (double axis) in ggplot2

I have a double-y-axis chart made in Excel . In Excel, this requires only basic skills. I would like to replicate this diagram using the ggplot2 library in R

enter image description here

I already did this, but I need to build the answer on 2nd-y-axis .

enter image description here

I am enclosing the reproducible code that I used:

 #Data generation Year <- c(2014, 2015, 2016) Response <- c(1000, 1100, 1200) Rate <- c(0.75, 0.42, 0.80) df <- data.frame(Year, Response, Rate) #Chart library(ggplot2) ggplot(df) + geom_bar(aes(x=Year, y=Response),stat="identity", fill="tan1", colour="sienna3")+ geom_line(aes(x=Year, y=Rate),stat="identity")+ geom_text(aes(label=Rate, x=Year, y=Rate), colour="black")+ geom_text(aes(label=Response, x=Year, y=0.9*Response), colour="black") 
+5
source share
1 answer

First scale Rate to Rate*max(df$Response) and scale the text 0.9 of the response text.

Second, enable the second axis via scale_y_continuous(sec.axis=...) :

 ggplot(df) + geom_bar(aes(x=Year, y=Response),stat="identity", fill="tan1", colour="sienna3")+ geom_line(aes(x=Year, y=Rate*max(df$Response)),stat="identity")+ geom_text(aes(label=Rate, x=Year, y=Rate*max(df$Response)), colour="black")+ geom_text(aes(label=Response, x=Year, y=0.95*Response), colour="black")+ scale_y_continuous(sec.axis = sec_axis(~./max(df$Response))) 

What gives:

enter image description here

+10
source

Source: https://habr.com/ru/post/1263097/


All Articles