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
You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))
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.
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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With