GGplot geom_point - how to get inherit.aes = FALSE to properly work?

28 Views Asked by At

I'm trying to plot a separate set of datapoints on an existing ggplot. The scenario is where one of my treatment means was thrown off by an anomalous replicate, so I was trying to show each replicate on the graph as well. However, I'm running into the "Aesthetics must be either length 1 or the same as the data" issue with geom_point, despite already specifying inherit.aes = FALSE.

See below reproducible sample.


#create dataset 
light <- c(1,2,3,1,2,3)
chlorophyll <- c(-50,20,30,5,10,15)
species <- c('grass','grass','grass','tree','tree','tree')
plot <- data.frame(light,chlorophyll,species)

#plot this information 
ggplot(plot, aes(x=light, y=chlorophyll,color=as.character(species))) +
  geom_point(size = 10, shape = "diamond") + 
  geom_line()+
  ggtitle('Chlorophyll') +
  theme_classic() +
  labs(color='Species') +
  xlab('Light') + ylab('Chlorophyll') 
#remove anomalous treatment
newplot <- filter(plot,light!=1  | species != 'grass')
#plot again
ggplot(newplot, aes(x=light, y=chlorophyll,color=as.character(species))) +
  geom_point(size = 10, shape = "diamond") + 
  geom_line()+
  ggtitle('Chlorophyll') +
  theme_classic() +
  labs(color='Species') +
  xlab('Light') + ylab('Chlorophyll') 
#produce sample replicates for anomalous treatment
anomalylight <- c(1,1,1)
anomalychlorophyll <- c(10,20,-180)
anomalyspecies <- c('grass','grass','grass')
anomaly <- data.frame(anomalylight,anomalychlorophyll,anomalyspecies)
#plot anomaly on with geom_point
ggplot(newplot, aes(x=light, y=chlorophyll,color=as.character(species))) +
  geom_point(size = 10, shape = "diamond") + 
  geom_line()+
  ggtitle('Chlorophyll') +
  theme_classic() +
  labs(color='Species') +
  xlab('Light') + ylab('Chlorophyll') +
  geom_point(data=anomaly,aes(x=light,y=chlorophyll),color='red',inherit.aes=FALSE)

This gives the aforementioned error; I don't understand why it is still inheriting the aesthetic of the first layer when I've already specified it not to.

Alternatively, I've seen people recommending to not specify aes in ggplot() so that the aesthetics don't get inherited, so I've tried (for the last code block)

#plot anomaly on with geom_point
ggplot() +
  geom_point(data=newplot, aes(x=light, y=chlorophyll,color=as.character(species)),size = 10, shape = "diamond") + 
  geom_line()+
  ggtitle('Chlorophyll') +
  theme_classic() +
  labs(color='Species') +
  xlab('Light') + ylab('Chlorophyll') +
  geom_point(data=anomaly,aes(x=light,y=chlorophyll),color='red',inherit.aes=FALSE)

but the same issue persists. Any help would be appreciated.

0

There are 0 best solutions below