Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

r - Combining Bar and Line chart (double axis) in ggplot2

I have double-y-axis chart made in Excel. In Excel it requires only basic skills. What I'd like to do is to replicate this chart using the ggplot2 library in R.

enter image description here

I have already done this, but I need to plot Response on 2nd-y-axis.

enter image description here

I enclose reproducible code I've 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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, scale Rate by Rate*max(df$Response) and modify the 0.9 scale of Response text.

Second, include a 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)))

Which yields:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...