我有一个 100% 堆叠条形图,条形宽度可变,但我希望条形上没有空格或重叠。这是我的示例数据和输出,没有scale_x_连续线。
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
我引用了以下线程,但无法获得适合我的场景的解决方案:
第一个链接没有使用堆叠图表,但解决了间隙问题。第二个链接正是我正在寻找的,但我无法使用示例数据重新创建解决方案。我错过了一些明显的东西吗?
图上方和周围的边距空间由
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))