Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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

like image 606
henryTi Avatar asked Aug 10 '20 19:08

henryTi


People also ask

How do I change the legend value in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))

How do I add a legend in ggplot2?

Adding a legend If you want to add a legend to a ggplot2 chart you will need to pass a categorical (or numerical) variable to color , fill , shape or alpha inside aes . Depending on which argument you use to pass the data and your specific case the output will be different.

How do I change the legend position in R?

You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.


1 Answers

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

like image 146
nniloc Avatar answered Oct 23 '22 04:10

nniloc