colinfang
colinfang

Reputation: 21737

Plotting geom_bar and geom_point together?

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.

Upvotes: 2

Views: 2483

Answers (1)

BrodieG
BrodieG

Reputation: 52647

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

Upvotes: 1

Related Questions