保留组合条形图中缺失列的位置。

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

一个很常见的问题是,当ggplot中缺少一列时,要保留条形图的宽度(如 1, 2. 除了这个修复之外,我还需要的是保留缺失的条形图的相对位置(即缺口应该是条形图本来的位置)。

ggplot(mtcars, aes(factor(cyl), fill = factor(gear))) +
  geom_bar(position = position_dodge(preserve = "single"))

结果--我还不能上传图片

你会注意到在8个气缸的组中(最右边)缺少了一列绿色(齿轮=4)。preserve="single" 已经修正了宽度,但蓝色的栏(齿轮=5)已经向左移动来填补这个空缺。

我怎样才能防止这种情况发生?我希望在绿色的地方有一个空白。

谢谢你的帮助。

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

我们得到的频率 count 基于'气缸'、'齿轮',用以下方法扩展数据。complete 以获得所有的组合,而 fill将计数列'n'设为0(默认情况下,所有没有在 complete 在有缺失组合的地方得到NA),然后用 ggplot

library(dplyr)
library(tidyr)
library(ggplot2)
mtcars %>%
   count(cyl, gear) %>%
   complete(cyl = unique(cyl), gear = unique(gear), 
         fill = list(n = 0)) %>%
   ggplot(aes(factor(cyl), n, fill = factor(gear))) + 
        geom_bar(stat = 'identity', position = 'dodge')
© www.soinside.com 2019 - 2024. All rights reserved.