Plotting geom_bar and geom_point together?

2019-07-24 15:52发布

data=data.frame(x=rep(0:9, each=2))

ggplot(data, aes(x=factor(x))) + geom_bar(alpha=0.5) + 
    geom_point(data=data.frame(x=0:10, y=2), aes(x=factor(x), y=y), alpha=0.5) 

ggplot(data, aes(x=factor(x))) + geom_bar(alpha=0.5) + 
    geom_point(data=data.frame(x=0:10, y=2), aes(x=factor(x), y=y), alpha=0.5) +
    scale_x_discrete(limits=0:10)

Also, do I have to factor given x is integer so it is discrete already? enter image description here Wrong order enter image description here Wrong x axis label.

标签: r ggplot2
1条回答
不美不萌又怎样
2楼-- · 2019-07-24 16:18
ggplot(data, aes(x=x)) + geom_bar(alpha=0.5) + scale_x_discrete(limits=0:10) + 
  geom_point(data=data.frame(x=0:10, y=2), aes(x=x, y=y), alpha=0.5)

You can force a discrete scale to get what you want. It is odd how when you mix geom_point() and geom_bar() ggplot starts ordering things in unexpected ways.

enter image description here

查看更多
登录 后发表回答