fish_dots
fish_dots

Reputation: 128

Annotate is giving error in ggplot2 when using facet

I had previously used annotate() to add letters to facet panels of ggplots. After updating R (to 3.6.1), code that had previously worked with annotate no longer does.

I can solve this by making a separate dataframe to label each facet, but that is cumbersome when I have a decent number of plots to make that vary in how many facets they have. All I want is a letter (e.g., a-f) on each panel for identification in a journal article.

library(ggplot2)

data(diamonds)

ggplot(diamonds, aes(x=carat,y=price)) +geom_point()+ facet_wrap(~cut) + annotate("text",label=letters[1:5],x=4.5,y=15000,size=6,fontface="bold")

ggplot(diamonds, aes(x=carat,y=price)) +geom_point()+ facet_wrap(~cut) + annotate("text",label=letters[1],x=4.5,y=15000,size=6,fontface="bold")

The first ggplot should produce a plot that has the facets labeled with lowercase letters. Instead, I get the error:

Error: Aesthetics must be either length 1 or the same as the data (25): label

The code does work if only one letter is used, as seen in the second ggplot, so annotate will work, but not with multiple values as it previously did.

Upvotes: 2

Views: 608

Answers (1)

TobiO
TobiO

Reputation: 1381

I usually always use an external data frame for faceted annotations, because it is more traceable to me.

df_labels=unique(diamonds[,"cut"])
df_labels$label=letters[as.numeric(df_labels$cut)] #to preserve factor level ordering
df_labels$x=4.5
df_labels$y=15000

ggplot(diamonds, aes(x=carat,y=price)) +
  geom_point()+ facet_wrap(~cut) + 
  geom_text(data=df_labels,aes(x=x,y=y,label=label))

Upvotes: 1

Related Questions