Home > OS >  Create stacked barplot with lower and upper limits
Create stacked barplot with lower and upper limits

Time:07-20

I have below dataframe and want to draw a ggplot with stacked bar for lower and upper limits with each data points.

library(ggplot2)
dat = rbind(data.frame('val' = c(3,4), 'val0' = c(1,2), 'val2' = c(5,6), 'name' = c('A', 'A')),
            data.frame('val' = c(3,4) 2, 'val0' = c(1,2) 2, 'val2' = c(5,6) 2, 'name' = c('B', 'B')))
dat

> dat
  val val0 val2 name
1   3    1    5    A
2   4    2    6    A
3   5    3    7    B
4   6    4    8    B

I am able to obtain below ggplot

ggplot(dat, aes(x = name))  
    geom_point(aes(y = val, color = name), size = 10, alpha = 0.3)

enter image description here

However I want to get below plot (hand-drawn - just for illustration)

enter image description here

Is there any way to draw above plot with my data?

Any pointer will be very helpful

CodePudding user response:

To get the rectangles, the easiest way is probably to use a modified box plot:

ggplot(within(dat, group <- c(1, 2, 1, 2)), aes(name, val, group = group))  
  geom_boxplot(stat = "identity", alpha = 0.5, color = "#00000030",
               aes(ymin = val0, lower = val0, fill = name, 
                   group = interaction(name, group),
                   ymax = val2, upper = val2, middle = val0),
               width = 0.5)  
  geom_point(position = position_dodge(width = 0.5), 
             aes(fill = name), shape = 21, size = 4)  
  scale_fill_brewer(palette = "Set1")  
  theme_minimal(base_size = 20)

enter image description here

CodePudding user response:

Maybe you want to use a dodged geom_pointrange like this:

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.1.2
dat = rbind(data.frame('val' = c(3,4), 'val0' = c(1,2), 'val2' = c(5,6), 'name' = c('A', 'A')),
            data.frame('val' = c(3,4) 2, 'val0' = c(1,2) 2, 'val2' = c(5,6) 2, 'name' = c('B', 'B')))

dat$fac <- factor(unlist(sapply(as.vector(table(dat$name)), seq_len)))

ggplot(dat)   
  geom_pointrange(aes(x=name,y=val,colour=name, 
                                ymin=val0,ymax=val2, group = fac), position=position_dodge(width=0.3)) 

Created on 2022-07-20 by the reprex package (v2.0.1)

  • Related