Plotting geom_bar and geom_point together?

2019-07-24 15:40发布

问题:

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? Wrong order Wrong x axis label.

回答1:

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.



标签: r ggplot2