Changing legend shape when geom_text() and colour aesthetic are used in ggplot2

When you use the geom_text() with the colour aesthetic is set, you get an ugly “a” in the legend with color. Let us first create a demo data.

library(tidyverse)
data(iris)
df <- iris %>% 
  sample_frac(size = 0.1) %>% 
  rowid_to_column("ID")

Here is how the data look. Yours will be different because of the random nature of sample_frac().

#    ID Sepal.Length Sepal.Width Petal.Length Petal.Width     Species
# 1   1          5.0         3.5          1.6         0.6      setosa
# 2   2          7.1         3.0          5.9         2.1   virginica
# 3   3          6.5         3.0          5.8         2.2   virginica
# 4   4          6.3         2.7          4.9         1.8   virginica
# 5   5          6.8         2.8          4.8         1.4  versicolor
# 6   6          6.2         2.9          4.3         1.3  versicolor
# 7   7          5.7         3.8          1.7         0.3      setosa
# 8   8          5.4         3.9          1.3         0.4      setosa
# 9   9          4.8         3.1          1.6         0.2      setosa
# 10 10          5.1         2.5          3.0         1.1  versicolor
# 11 11          6.4         2.9          4.3         1.3  versicolor
# 12 12          5.7         4.4          1.5         0.4      setosa
# 13 13          5.1         3.4          1.5         0.2      setosa
# 14 14          4.4         2.9          1.4         0.2      setosa
# 15 15          5.0         3.3          1.4         0.2      setosa

Default plot

ggplot(df, aes(Sepal.Length, Sepal.Width, label=ID, col=Species)) +
  geom_text(size=6) +
  theme_bw() +
  labs(title="Default")

Notice the ugly “a” in the legend?

Alternative 1 – hide the legend

One simple option is to simply hide the legend by setting show.legend=FALSE in geom_text().

ggplot(df, aes(Sepal.Length, Sepal.Width, label=ID, col=Species)) +
  geom_text(show.legend=FALSE) +
  theme_bw() 

Alternative 2 – make a better legend

The other alternative is slightly more complex.

  • disable the legend aesthetic in geom_text() via the show.legend parameter
  • add transparent point in geom_point() by setting alpha=0 so no points are added to plot. This geom_point() will trigger the legend aesthetic
  • control the legend aesthetic for geom_point via guides()
ggplot(df, aes(Sepal.Length, Sepal.Width, label=ID, col=Species)) +
  geom_text(show.legend=FALSE) +
  geom_point(alpha=0) +
  guides(colour = guide_legend(title="Variety", override.aes=list(alpha=1, shape=15, size=6))) + 
  theme_bw()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s