首页 > 解决方案 > 使用堆栈和闪避制作条形图,并保持闪避的条相互接触

问题描述

我的数据如下:

library(ggplot2)
library(tidyr)
library(dplyr)

DT <- structure(list(value = structure(c(2, 3, 3, 4, 4, 5, 6, 6, 7, 
7, 8, 8, 9, 9, 1, 1, 2, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9
), label = NA_character_, class = c("labelled", "numeric")), 
    penalty = structure(c(0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 
    0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1), label = "", class = c("labelled", 
    "numeric")), count = c(1L, 1L, 2L, 3L, 3L, 5L, 11L, 2L, 30L, 
    10L, 48L, 13L, 62L, 16L, 1L, 1L, 1L, 2L, 7L, 4L, 10L, 4L, 
    19L, 6L, 33L, 7L, 39L, 10L, 50L, 13L), type = c("Truth", 
    "Truth", "Truth", "Truth", "Truth", "Truth", "Truth", "Truth", 
    "Truth", "Truth", "Truth", "Truth", "Truth", "Truth", "Tax", 
    "Tax", "Tax", "Tax", "Tax", "Tax", "Tax", "Tax", "Tax", "Tax", 
    "Tax", "Tax", "Tax", "Tax", "Tax", "Tax"), x_label = c("2_Truth", 
    "3_Truth", "3_Truth", "4_Truth", "4_Truth", "5_Truth", "6_Truth", 
    "6_Truth", "7_Truth", "7_Truth", "8_Truth", "8_Truth", "9_Truth", 
    "9_Truth", "1_Tax", "1_Tax", "2_Tax", "3_Tax", "4_Tax", "4_Tax", 
    "5_Tax", "5_Tax", "6_Tax", "6_Tax", "7_Tax", "7_Tax", "8_Tax", 
    "8_Tax", "9_Tax", "9_Tax")), row.names = c(NA, -30L), class = c("data.table", 
"data.frame"))

   value penalty count  type x_label
 1:     2       0     1 Truth 2_Truth
 2:     3       0     1 Truth 3_Truth
 3:     3       1     2 Truth 3_Truth
...
28:     8       1    10   Tax   8_Tax
29:     9       0    50   Tax   9_Tax
30:     9       1    13   Tax   9_Tax

我尝试按照肯特约翰逊在此链接中的建议进行“带有堆栈和闪避的条形图”,如下所示:

ggplot(DT, aes(x=x_label, y=count, fill=penalty)) +
  geom_bar(stat='identity') + labs(x='Value / Treatment') + 
  theme(legend.title = element_blank(), legend.position = c(0.1, 0.85))

在此处输入图像描述

但是,我希望图表更像下面的图表(这就是我开始的方式)。至少具有相同值的条在一起但颜色不同。如果可能,还可以使用密度函数、图例和 x 轴值。

有没有办法做到这一点?

在此处输入图像描述

编辑:brianavery的建议

在此处输入图像描述

标签: rggplot2

解决方案


你可以试试

DT %>%
  mutate(value =as.character(value)) %>% 
  complete(crossing(value,type, penalty), fill = list(count = NA)) %>% 
  ggplot(aes(x= value, y=count, fill =  type)) +
  geom_col(data = . %>% filter(penalty==0), position = position_dodge(width = 0.9), alpha = 0.2) + 
  geom_col(data = . %>% filter(penalty==1), position = position_dodge(width = 0.9), alpha = 1)  +
  geom_tile(aes(y=NA_integer_, alpha = factor(penalty)))

在此处输入图像描述


推荐阅读