我有以下用geom_bar
制作的堆叠式条形图。
问题:如何在每个fill
周围添加与cols
中匹配颜色相对应的轮廓。棘手的部分是,轮廓线不应位于每个fill
之间,而应位于“边界”和顶部之间(排他(预期的输出如下))
我有
与
一起写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))
预期输出
我的数据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")
答案 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=
必须比正常情况要高得多,因为白色矩形最终会覆盖线的一半。