Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

add significance asterisk manually in ggplot2

I have a time series DataFrame in R.
There are 4 groups and the data of each group (variable) is acquired at 3 different timepoints.

Group Timepoint Variable 
A        1 1.4705745 
B        1 4.6090900
C        1 2.2480962
D        1 1.6443650
E        1 4.4812444
A        2 0.8026552
B        2 4.7803944
C        2 1.3743527
D        2 4.0399467
E        2 3.5651057 
A        3 4.7275369
B        3 2.4491532
C        3 3.9508347
D        3 3.4278974
E        3 0.6917490

I made a line plot using the following code,

plot_data <- ggplot(data, aes(x = Timepoint, y = Variable, color = Group, group = Group))+geom_line()+
  scale_color_discrete("Group")+
  scale_y_continuous(limits = c(0, 6))
plot_data

enter image description here
but also want to add significant asterisk, for instance, like that.
enter image description here
Is there any way to add asterisk to the plot manually?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use annotate like this:

library(ggplot2)
plot_data <- ggplot(data, aes(x = Timepoint, y = Variable, color = Group, group = Group))+geom_line()+
  scale_color_discrete("Group")+
  scale_y_continuous(limits = c(0, 6)) +
  annotate('text', x = 1, y = c(5,5.2), label='"*"', parse=TRUE, color = c("pink", "yellow")) +
  annotate('text', x = 3, y = c(5,5.2), label='"*"', parse=TRUE, color = c("red", "green"))

plot_data

Created on 2022-09-02 with reprex v2.0.2

To get the exact same colors as in standard ggplot you can check that by using hue_pal like this:

library(ggplot2)
library(scales)
show_col(hue_pal()(5))

plot_data <- ggplot(data, aes(x = Timepoint, y = Variable, color = Group, group = Group))+geom_line()+
  scale_color_discrete("Group")+
  scale_y_continuous(limits = c(0, 6)) +
  annotate('text', x = 1, y = c(5,5.2), label='"*"', parse=TRUE, color = c("#A3A500", "#E76BF3")) +
  annotate('text', x = 3, y = c(5,5.2), label='"*"', parse=TRUE, color = c("#F8766D", "#00BF7D"))

plot_data

Created on 2022-09-02 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading