在ggplot2的堆积条形图中是否可以在堆叠之间添加空间?

13

我从这里借鉴了这个例子:

DF <- read.table(text="Rank F1     F2     F3
1    500    250    50
2    400    100    30
3    300    155    100
4    200    90     10", header=TRUE)

library(reshape2)
DF1 <- melt(DF, id.var="Rank")

library(ggplot2)
ggplot(DF1, aes(x = Rank, y = value, fill = variable)) + 
geom_bar(stat = "identity")

使用ggplot2是否可以创建像以下图表一样的堆积条形图?我不想通过不同的颜色来区分堆叠。

输入图像描述

编辑:根据Pascal的评论,

ggplot(DF1, aes(x = Rank, y = value)) + 
geom_bar(stat = "identity",lwd=2, color="white")

在此输入图片描述

我的柱状图仍有白边。


2
geom_bar 中,您可以添加其他参数,例如 colorlwd - user3710546
颜色不是问题,堆栈之间的空间不能用 lwd 解决。 - Soheil
你至少试过了吗? - user3710546
我可以发布结果。也许我漏掉了什么。 - Soheil
1
现在你有了一个空间。 - user3710546
显示剩余3条评论
1个回答

9

这是我能够接近你的示例图的最佳匹配。它并没有比你已经整理好的图像有多大的改进,但是对灰色背景上的白色条形边框的强调更少。

library(ggplot2)
p <- ggplot(DF1, aes(x = Rank, y = value, group = variable))
p <- p + geom_bar(stat = "identity", position = "stack", lwd = 1.5,
                  width = 0.5, colour = "white", fill = "black")        
p <- p + theme_classic()
p <- p + theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
p

那将产生以下结果:

如果您想保留灰色背景,可以找出确切的灰色阴影,并在去除背景网格的同时使用该颜色作为线条颜色(但这不是正确的阴影)。
p <- ggplot(DF1, aes(x = Rank, y = value))
p <- p + geom_bar(stat = "identity", position = "stack", lwd = 1.5,
                  width = 0.5, colour = "grey", fill = "black")        
p <- p + theme(panel.grid = element_blank())
p

这种解决方案的问题在于非常小的组可能无法显示出来(例如,当排名=4变量F3=10时;这个小值完全被白色条形轮廓覆盖)。

您的样本数据:

DF1 <- structure(list(Rank = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 
3L, 4L), variable = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 
3L, 3L, 3L, 3L), .Label = c("F1", "F2", "F3"), class = "factor"), 
    value = c(500L, 400L, 300L, 200L, 250L, 100L, 155L, 90L, 
    50L, 30L, 100L, 10L)), row.names = c(NA, -12L), .Names = c("Rank", 
"variable", "value"), class = "data.frame")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接