How to overlay geom_bar and geom_line plots with different number of elements using ggplot2?

情到浓时终转凉″ 提交于 2019-12-04 21:21:37

Try this

p <- ggplot() 
p <- p + geom_bar(data = a, aes(x=x, y=y, fill=z), position="stack",stat="identity")
p <- p + geom_line(data = b, aes(x=x, y=y/max(y)), stat="identity") 
p

Update: You can rescale the one y to make them the same. As I don't know the relations between the two ys, I rescaled them by using y/max(y). Does this solve you problem?

Try merging the datasets first, then plotting, like this:

require(ggplot2)

df <- merge(a,b,by="x")

ggplot(df, aes(x=x, y=y.x, fill=z)) +
  geom_bar(position="stack",stat="identity") + 
  geom_line(aes(x=x, y=y.y)) + 
  ylab("") + xlab("x")

Output:

I edited the sample data to better illustrate the effects, because the y-axis scaling of the original data would not have matched well:

a <-data.frame(x=c(1,1,1,2,2,2,3,3,3),
               y=c(0.3,0.4,0.3,0.2,0.5,0.3,0.4,0.4,0.2), 
               z=c("do","re","mi","do","re","mi","do","re","mi"))

b <- data.frame(x=c(1,2,3),y=c(.4,1,.4))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!