Draw lines between different elements in a stacked bar plot

后端 未结 3 2032
無奈伤痛
無奈伤痛 2020-12-09 20:48

I\'m trying to draw lines between two separate stacked bars (same plot) in ggplot2 to show that two segments of the second bar are a subset of the first bar.

I have

3条回答
  •  旧时难觅i
    2020-12-09 21:14

    You could do that:

    library(data.table)
    library(ggplot2)
    Example <- data.table(X_Axis = c('Count', 'Count', 'Dollars', 'Dollars', 'Dollars'),
                          Stack_Group = c('Purely A', 'A & B', 'Purely A Dollars', 'B Mixed Dollars', 'A Mixed dollars'),
                          Value = c(10,3, 120000, 100000, 50000))
    Example[, Percent := Value/sum(Value), by = X_Axis]
    
    ggplot(Example) +
      geom_segment(data=data.frame(x=c("Count","Count"),
                                   xend=c("Dollars","Dollars"),
                                   y=c(1,0.94),
                                   yend=c(1,0.27)),aes(x=x,y=y,xend=xend,yend=yend))+
      geom_bar(aes(x = X_Axis, y = Percent, fill=factor(Stack_Group)),stat='identity', width = .5) + 
      scale_y_continuous(labels = scales::percent)
    

    Which gives:

    NB: Because the x-axis is categorical we run into the problem of having the segment starting from this point and not from the border of the bars themselves. This is the reason why I draw geom_segment and then geom_bar so that the latter is over the first.
    Here the values were set manually, however using trigonometry and the width it is possible to calculate the offset value required to have the desired look.

提交回复
热议问题