ggplot:如何在堆叠的条形图中的每个填充周围添加轮廓,但仅部分添加

时间:2020-05-10 06:31:16

标签: r ggplot2 plot bar-chart

我有以下用geom_bar制作的堆叠式条形图。

问题:如何在每个fill周围添加与cols中匹配颜色相对应的轮廓。棘手的部分是,轮廓线不应位于每个fill之间,而应位于“边界”和顶部之间(排他(预期的输出如下))

我有

enter image description here

一起写
library(ggplot)
cols = c("#E1B930", "#2C77BF","#E38072","#6DBCC3", "grey40","black")

ggplot(i, aes(fill=uicc, x=n)) + theme_bw() +

  geom_bar(position="stack", stat="count") +

  scale_fill_manual(values=alpha(cols,0.5)) 

预期输出

enter image description here

我的数据i

i <- structure(list(uicc = structure(c(4L, 4L, 4L, 4L, 3L, 4L, 4L, 
4L, 4L, 3L, 4L, 3L, 4L, 2L, 4L, 4L, 4L, 1L, 4L, 4L, 2L, 4L, 4L, 
3L, 4L, 4L, 4L, 4L, 3L, 2L, 4L, 4L, 3L, 3L, 3L, 3L, 1L, 3L, 4L, 
4L, 2L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 4L, 4L, 4L, 4L, 4L, 4L, 3L, 
4L, 1L, 3L, 1L, 4L, 4L, 3L, 1L, 2L, 1L, 3L, 3L, 3L, 4L, 3L, 4L, 
4L, 3L, 4L, 3L, 3L, 3L, 2L, 2L, 4L, 3L, 4L, 2L, 1L, 1L, 4L, 4L, 
4L, 4L, 1L, 4L, 4L, 4L, 4L, 4L, 4L, 2L, 3L, 3L, 4L), .Label = c("1", 
"2", "3", "4"), class = "factor"), n = structure(c(4L, 4L, 4L, 
4L, 2L, 1L, 4L, 1L, 4L, 2L, 4L, 2L, 4L, 1L, 4L, 5L, 2L, 1L, 1L, 
5L, 1L, 1L, 2L, 2L, 1L, 4L, 3L, 4L, 2L, 1L, 5L, 2L, 2L, 2L, 2L, 
2L, 1L, 2L, 3L, 2L, 1L, 4L, 2L, 1L, 4L, 1L, 4L, 1L, 2L, 2L, 2L, 
4L, 1L, 4L, 2L, 4L, 1L, 1L, 1L, 4L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 
1L, 1L, 2L, 4L, 1L, 1L, 4L, 2L, 2L, 2L, 1L, 1L, 3L, 2L, 5L, 1L, 
1L, 1L, 4L, 4L, 4L, 5L, 1L, 4L, 4L, 1L, 4L, 2L, 1L, 1L, 2L, 2L, 
4L), .Label = c("0", "1", "2", "3", "4", "5"), class = "factor")), row.names = c(NA, 
100L), class = "data.frame")

1 个答案:

答案 0 :(得分:3)

好吧,我找到了办法。

没有简单的方法来绘制“外部”线,因此我使用的方法是继续进行geom_bar调用。通过在初始geom_bar调用上方绘制白色矩形来“擦除”内部线条,然后以无色的color=美学方式重新填充填充。

为了在最初的geom_bar调用上绘制矩形,我创建了i的摘要数据框,它设置了y值。

i.sum <- i %>% group_by(n) %>% tally()

ggplot(i, aes(x=n)) + theme_bw() +

  # draw lines
  geom_bar(position='stack', stat='count',
      aes(color=uicc), fill=NA, size=1.5) +

  # cover over those inner lines
  geom_col(data=i.sum, aes(y=nn), fill='white') +

  # put back in the fill
  geom_bar(position='stack', stat='count',
      aes(fill=uicc), color=NA) +

  scale_fill_manual(values=alpha(cols,0.5)) +
  scale_color_manual(values=cols)

请注意,size=美学中的color=必须比正常情况要高得多,因为白色矩形最终会覆盖线的一半。

enter image description here