Home > other >  How can I visually separate each value within a bar in geom_bar?
How can I visually separate each value within a bar in geom_bar?

Time:04-15

I am trying to make a ggplot figure with geom_bar where each value within a bar is visually separated:

What I have vs. what I'm trying to make:

enter image description here

It seems simple but I have not been able to find a way to accomplish it. I'm probably missing an obvious solution. Thanks in advance.

Example code:

library(ggplot2)
mydata <- data.frame(id = c("exp1", "exp2", "exp3"),
                     value = c(2, 4, 3)
                     )

ggplot(mydata, aes(x = id, y = value))  
  geom_bar(stat = "identity", fill = NA, colour = "black")

CodePudding user response:

We can do this by making each segment of each bar it's own row and creating a group aesthetic for each row:

dat_long = mydata[rep(1:nrow(mydata), times = mydata$value), ]
dat_long$uid = 1:nrow(dat_long)
ggplot(dat_long, aes(x = id, group = uid))  
  geom_bar(fill = NA, colour = "black")

enter image description here

CodePudding user response:

Another option would be to create a new column with a number sequence decreasing to 1, then unnest to create the additional rows. Then, use the second dataframe in geom_segment.

library(tidyverse)

mydata2 <- mydata %>%
  group_by(id) %>%
  mutate(value_line = list(value:1),
         id = parse_number(id)) %>%
  unnest(value_line)

ggplot(mydata, aes(x = id, y = value))  
  geom_bar(stat = "identity", fill = NA, colour = "black")  
  geom_segment(data=mydata2, aes(x=id-0.45, xend=id 0.45, y=value_line, yend=value_line))

Output

enter image description here

  • Related