Home > Mobile >  In dodge bar plot how to add variance label (include lines point label)
In dodge bar plot how to add variance label (include lines point label)

Time:04-15

In dodge bar plot as 'Current_plot', I want to add YOY variance label as 'Wished plot'. Is the any package or function for this ? Thanks!

plot_df <- data.frame(year=c("2022","2021","2022","2021","2022","2021"),
month=c("1","1","2","2","3","3"),
amount=c(2,1,3,2,2,6))


Current_plot <- plot_df %>% ggplot(aes(x=month,y=amount,fill=year)) 
  geom_bar(position = 'dodge',stat='identity') 
  geom_text(aes(label=amount),size=6,
            position = position_dodge(0.8),
            vjust=1.5)

Current_plot

enter image description here

CodePudding user response:

You can use the package ggsignif to add annotations to the plot. It's very manual, but should get you started.

library(ggplot2)
library(ggsignif)

plot_df <- data.frame(year=c("2022","2021","2022","2021","2022","2021"),
                      month=c("1","1","2","2","3","3"),
                      amount=c(2,1,3,2,2,6))


ggplot(plot_df, aes(x=month,y=amount,fill=year)) 
  geom_bar(position = 'dodge',stat='identity') 
  geom_text(aes(label=amount),size=6,
            position = position_dodge(0.8),
            vjust=1.5)  
  geom_signif(
    y_position = c(2.5, 3.5, 6.5), 
    xmin = seq(0.7, 2.7, 1), 
    xmax = seq(1.3, 3.3, 1),
    annotation = c("1", "1", "4"), 
    tip_length = c(0.3, 0.1, 0.3, 0.1, 0.1, 0.9)
  )

Created on 2022-04-15 by the reprex package (v2.0.1)

  • Related