1

I have two df that I used for plotting.

df <- data.frame(x2=rnorm(100),y2=rnorm(100)) %>% mutate(Class=case_when(x2>0 ~1,
                                                                         TRUE ~0))
df2<- structure(list(xpos = -2.5, ypos = -2, annotateText = structure(1L, .Label = "Text", class = "factor"), 
    hjustvar = 0, vjustvar = 0), class = "data.frame", row.names = c(NA, 
-1L))

My plotting codes are:

ggplot(df, aes(x2, y2, colour=Class)) + geom_point()+
  geom_text(data = df2, aes(x=xpos,y=ypos,hjust=hjustvar,
                                    vjust=vjustvar,label=(annotateText)))

When I run it, I got error codes: Error in FUN(X[[i]], ...) : object 'Class' not found. If I removed colour=Class then my codes run. What did I do wrong? I really want to have the color difference for different groups. Any suggestion?

Stataq
  • 2,237
  • 6
  • 14

2 Answers2

2

The color = Class can be moved into geom_point as the subsequent layers can check for inheritance from the top layer as by default inherit.aes = TRUE in those layers

library(ggplot2)
ggplot(df, aes(x2, y2)) +
     geom_point(aes(color = Class)) + 
     geom_text(data = df2, aes(x = xpos,y = ypos,hjust = hjustvar,
                        vjust = vjustvar,label= annotateText))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • May I ask why I can use `color = Class` in the first line? – Stataq Apr 16 '21 at 21:23
  • Ah didn't realise it worked like that! Geoms only inherit from the initial `ggplot()` call – Captain Hat Apr 16 '21 at 21:27
  • @Stataq The reason is mentioned [here](https://stackoverflow.com/questions/40391272/ggplot-object-not-found-error-when-adding-layer-with-different-data) about inheriting – akrun Apr 16 '21 at 21:27
2

Your second geometry is inheriting the aesthetics you specified in your initial call to ggplot()

You need to specify inherit.aes = FALSE in your call to geom_text()

Ggplot geometries inherit the aesthetics from the initial call to ggplot(). Your aesthetic colour = Class that you specify in your call to ggplot() is inherited by geom_point(), resulting in the desired behaviour. Your error occurs because geom_text() also inherits this colour = Class, and subsequently crashes because Class isn't defined in the data it's using - df2.

You can fix this by specifying in geom_text() that you don't want to inherit any aesthetics from the initial call:


ggplot(df, aes(x2, y2, colour=Class)) + geom_point() +
  geom_text(data = df2, aes(x=xpos,y=ypos,hjust=hjustvar,
                            vjust=vjustvar,label=(annotateText)),
            inherit.aes = FALSE)

Captain Hat
  • 2,444
  • 1
  • 14
  • 31