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
584 views
in Technique[技术] by (71.8m points)

r - geom_bar + geom_line: with different y-axis scale?

Is there any way to plot geom_bar with geom_line like the following chart.

enter image description here

I have come up with the two separate charts. How to combine them with two different axes on the left and right sides respectively.

library(ggplot2)
temp = data.frame(Product=as.factor(c("A","B","C")),
                  N = c(17100,17533,6756),
                  n = c(5,13,11),
                  rate = c(0.0003,0.0007,0.0016),
                  labels = c(".03%",".07%",".16%"))

p1 = ggplot(data = temp, aes(x=Product,y=N))+
  geom_bar(stat="identity",fill="#F8766D")+geom_text(aes(label=n,col="red",vjust=-0.5))+
  theme(legend.position="none",axis.title.y=element_blank(),axis.text.x = element_text(angle = 90, hjust = 1))
  p1
p2 = ggplot(data = temp,aes(x=Product,y=rate))+
  geom_line(aes(group=1))+geom_text(aes(label=labels,col="red",vjust=0))+
  theme(legend.position="none",axis.title.y=element_blank(),
        axis.text.x = element_text(angle = 90, hjust = 0))+
  xlab("Product")
p2

Thanks a lot.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Now that ggplot2 has added support for secondary axes (as of version 2.2.0), it is possible to create a graph like this with much less code, within a single ggplot() call (no stacking multiple plots as a workaround!)

ggplot(data = temp, aes(x = Product, y = N)) + #start plot by by plotting bars
  geom_bar(stat = "identity") + 
  #plot line on same graph
  # rate multiplied by 10000000 to get on same scale as bars
  geom_line(data = temp, aes(x = Product, y = (rate)*10000000, group = 1), 
            inherit.aes = FALSE) +
  #specify secondary axis
  #apply inverse of above transformation to correctly scale secondary axis (/10000000)
  scale_y_continuous(sec.axis = sec_axis(~./10000000, name = "rate"))

enter image description here

I know this is an older question that has an answer, but wanted to provide an update - due to package updates there is an simpler solution than the one in the accepted answer (which was the best solution at the time).


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

...