【问题标题】:Is it possible to put space between stacks in ggplot2 stacked bar?是否可以在 ggplot2 堆叠条中的堆栈之间放置空间?
【发布时间】:2015-05-01 02:56:56
【问题描述】:

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

编辑:基于 Pascal 的 cmets,

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

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

【问题讨论】:

  • geom_bar中,可以添加其他参数,如colorlwd
  • 颜色不是问题,栈间距不能用lwd解决
  • 您至少尝试过吗?
  • 我可以发布结果。也许我错过了什么。
  • 现在你有一个空间。

标签: r ggplot2 stacked-chart


【解决方案1】:

这是我能找到的最接近你的示例图的地方。与您已经排序的内容相比,它并没有太大的改进,但不太强调灰色背景上的白条边框。

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")

【讨论】:

    猜你喜欢
    • 2018-01-23
    • 1970-01-01
    • 2011-07-18
    • 2015-06-22
    • 2021-10-01
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多