100% 堆叠条形图,条形宽度可变,但没有空间间隙或重叠

问题描述 投票:0回答:1

我有一个 100% 堆叠条形图,条形宽度可变,但我希望条形上没有空格或重叠。这是我的示例数据和输出,没有scale_x_连续线。


output chart

library(ggplot2)

df <- data.frame(x = c("A","A","B","B","C","C"), group = c("L","R","L","R","L","R"),width = c(0.1,0.1,0.50,0.50,0.40,0.40), y = c(0.75,0.25,0.5,0.5,0.9,0.1))

pos <- 0.5 * (cumsum(df$width) + cumsum(c(0, df$width[-length(df$width)])))


g <-ggplot(df, aes(x = x, y = y, width = width*2, fill = group)) + 
    geom_bar(stat = "identity", color = "white" ) +
    scale_x_continuous(breaks = pos)
g

我引用了以下线程,但无法获得适合我的场景的解决方案:

如何使ggplot2中的可变条形宽度不重叠或间隙

ggplot 中的 Spineplots 或至少垂直标签

第一个链接没有使用堆叠图表,但解决了间隙问题。第二个链接正是我正在寻找的,但我无法使用示例数据重新创建解决方案。我错过了一些明显的东西吗?

r ggplot2 geom-bar
1个回答
0
投票

图上方和周围的边距空间由

expansion
函数的
scale_y_x()
参数控制(在您的情况下,
scale_y_continuous
scale_x_discrete
)。之所以称为扩展,是因为它是一个乘法因子,会增加条形顶部和下方的空间,因此将扩展设置为 0 将删除绘图周围的任何额外空间。因此,您可以像这样删除此扩展边距:

library(ggplot2)

df <- data.frame(x = c("A","A","B","B","C","C"), group = c("L","R","L","R","L","R"),width = c(0.1,0.1,0.50,0.50,0.40,0.40), y = c(0.75,0.25,0.5,0.5,0.9,0.1))

pos <- 0.5 * (cumsum(df$width) + cumsum(c(0, df$width[-length(df$width)])))


ggplot(df, aes(x = x, y = y, width = width*2, fill = group)) + 
  geom_bar(stat = "identity", color = "white") +
  scale_y_continuous(expand = expansion(0)) +
  scale_x_discrete(expand = expansion(0))

© www.soinside.com 2019 - 2024. All rights reserved.