henryTi
henryTi

Reputation: 131

How can I add an extra symbol in legend of a ggplot graph?

I want to add a symbol to the legend of the ggplot graph. Symbolic code of the ggplot is represented below, my question is, how can I draw that (*) symbol circled in the picture?

  library(ggplot2 )
ToothGrowth$dose <- as.factor(ToothGrowth$dose)
p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + 
  geom_boxplot()
p

enter image description here

Upvotes: 6

Views: 1228

Answers (1)

nniloc
nniloc

Reputation: 4243

This takes some manual tweaking to get the positioning right, but you can add a symbol as an annotation outside of a plot using annotate and coord_cartesian with clip = off. Some hints taken from this answer.

ToothGrowth$dose <- as.factor(ToothGrowth$dose)

p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + 
  geom_boxplot() +
  annotate("point", x = 3.66, y = 18.5, shape = 8, size = 2) +
  coord_cartesian(xlim = c(1, 3), clip = "off")

ggsave('test.jpg', p)

enter image description here


Edit: the shape in the above answer will be hidden by the legend if there is overlap. Using a tag is a similar solution but will allow the symbol to be plotted on top of the legend. It still takes some manual tweaking but the coordinates are positional to the figure not the data (which seems like a benefit).

ToothGrowth$dose <- as.factor(ToothGrowth$dose)

p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=dose)) + 
  geom_boxplot() +
  labs(tag = '*') +
  theme(plot.tag.position = c(.94, 0.5),
        plot.tag = element_text(size = 30))

ggsave('test.jpg', p)

enter image description here

Upvotes: 5

Related Questions