djdick
djdick

Reputation: 189

r facet_wrap not grouping properly with geom_point

I'm struggling with facet_wrap in R. It should be simple however the facet variable is not being picked up? Here is what I'm running:

plot = ggplot(data = item.household.descr.count, mapping = aes(x=item.household.descr.count$freq, y = item.household.descr.count$descr, color = item.household.descr.count$age.cat)) + geom_point() 
plot = plot + facet_wrap(~ age.cat, ncol = 2)
plot

resulting plot

I colored the faceting variable to try to help illustrate what is going on. The plot should have only one color in each facet instead of what you see here. Does anyone know what is going on?

Upvotes: 2

Views: 4656

Answers (1)

Didzis Elferts
Didzis Elferts

Reputation: 98579

This error is caused by fact that you are using $and data frame name to refer to your variables inside the aes(). Using ggplot() you should only use variables names in aes() as data frame is named already in data=.

plot = ggplot(data = item.household.descr.count, 
                mapping = aes(x=freq, y = descr, color = age.cat)) + geom_point() 
plot = plot + facet_wrap(~ age.cat, ncol = 2)
plot

Here is an example using diamonds dataset.

diamonds2<-diamonds[sample(nrow(diamonds),1000),]

ggplot(diamonds2,aes(diamonds2$carat,diamonds2$price,color=diamonds2$color))+geom_point()+
          facet_wrap(~color)

enter image description here

ggplot(diamonds2,aes(carat,price,color=color))+geom_point()+
  facet_wrap(~color)    

enter image description here

Upvotes: 5

Related Questions