Home > OS >  add significance asterisk manually in ggplot2
add significance asterisk manually in ggplot2

Time:09-03

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?

CodePudding user response:

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

  • Related