r - 是否可以在 ggplot2 堆叠条中的堆叠之间放置空间?

标签 r ggplot2 stacked-chart

我从 here: 拿了这个例子

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 创建如下图所示的堆叠条形图?我不想用不同的颜色来区分堆栈。

enter image description here

编辑:根据帕斯卡的评论,
ggplot(DF1, aes(x = Rank, y = value)) + 
geom_bar(stat = "identity",lwd=2, color="white")

enter image description here

我仍然有条形的白色边框。

最佳答案

这是我能得到的最接近你的示例图。除了您已经排序的内容之外,它并没有太大的改进,但不太强调灰色背景上的白色条形边框。

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

此解决方案的一个问题是不会看到非常小的组(例如,当 Rank = 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")

关于r - 是否可以在 ggplot2 堆叠条中的堆叠之间放置空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29981027/

相关文章:

r - 重叠堆积密度图

r - 使用 grid.curve 连接不同视点的 grobs

R:如果已经加载,则重新加载 google chrome URL

R函数根据索引将数据帧拆分为多个数据帧

r - 如何从 R 中的另一个函数调用的函数中提取变量的名称?

r - 仅对某些组添加回归线ggplot

r - 用绘图法保持尾随零

r - 连续变化的线宽在ggplot中变得透明

r - 如何对每个 ggplot 方面的堆栈进行排序?

r - R 中的堆叠条形图