Home > Blockchain >  How to insert IDs into the barcharts in R
How to insert IDs into the barcharts in R

Time:12-14

Here is a hypothetical samp;e of my data :

dd<-read.table (text=" ID   Group
1   A
2   C
4   A
9   B
6   A
8   B
12  A
5   C

", header=TRUE)

I want to insert IDs inside the bars for each group. This will give me the following plot.

enter image description here

CodePudding user response:

Using ggplot2 and a bit of dplyr for the data wrangling you could achieve your desired result like so:

EDIT Added ggtext::geom_textbox for automatic line breaks.

set.seed(123)

dd <- data.frame(
  Group = sample(LETTERS[1:3], 100, replace = TRUE),
  ID = 1:100
)

library(ggplot2)
library(dplyr)

dd <- dd %>%
  group_by(Group) |>
  summarise(n = n(), label = paste(ID, collapse = ", "))

pal_fill <- c("#90EE90", "#FFFF00", "#F0E68C")

ggplot(dd, aes(Group, n, fill = Group))  
  geom_col(color = "black")  
  geom_text(aes(label = n), vjust = 0, nudge_y = 1)  
  ggtext::geom_textbox(aes(label = label),
    vjust = 1, nudge_y = -1,
    hjust = .5, nudge_x = 0, box.color = NA,
    maxwidth = .45
  )  
  scale_fill_manual(values = pal_fill)  
  scale_y_continuous(expand = c(0, 0, .05, 0))  
  theme_bw()  
  theme(
    panel.border = element_blank(), panel.grid = element_blank(),
    axis.line.y = element_line(), axis.ticks.x = element_blank(),
    axis.ticks.length.y = unit(5, "pt")
  )  
  labs(x = NULL, y = NULL)  
  guides(fill = "none")

enter image description here

  • Related