ggplot2:gem_bar,具有按小平面比例和填充参数

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

我正在尝试使用geom_bar()fillfacet_grid结合起来绘制比例。

library(tidyverse)
set.seed(123)
df <- data_frame(val_num = c(rep(1, 60), rep(2, 40), rep(1, 30), rep(2, 70)),
                 val_cat = ifelse(val_num == 1, "cat", "mouse"),
                 val_fill = sample(c("black", "white", "gray"), 200, replace = TRUE), 
                 group = rep(c("A", "B"), each = 100))


ggplot(df) + 
  stat_count(mapping = aes(x = val_cat, y = ..count../tapply(..count.., ..x.. , sum)[..x..], 
                           fill = val_fill),
             position = position_dodge2(preserve = "single")) + 
  facet_grid(.~ group)

但是,似乎对A和B类中的所有猫(或所有小鼠)一起计算了比例。换句话说,前三列的比例之和不是1。

应该通过在group = group中添加mapping来解决。但是:

ggplot(df) + 
  stat_count(mapping = aes(x = val_cat, y = ..count../tapply(..count.., ..x.. , sum)[..x..], 
                           fill = val_fill, group = group),
             position = position_dodge2(preserve = "single")) + 
  facet_grid(.~ group)

plot忽略fill参数(而且不能解决问题)。我试图指定具有不同选择的组,包括interaction(),但没有任何实际的成功。

我想解决ggplot中的问题,并且希望避免在绘制之前进行数据操作。

r ggplot2 fill facet-grid
1个回答
0
投票

所以这并不像我想的那么容易,因为我不倾向于使用stat_xxx()函数。尽管您似乎坚持不事先处理数据,但可以使用以下方法。

grouped.df <- df %>%
  group_by( group, val_fill ) %>%
  count( val_cat ) %>%
  ungroup() %>%
  group_by( group, val_cat ) %>%
  mutate( prop=n/sum(n) ) %>%
  ungroup()

grouped.df %>%
  ggplot() +
  geom_col( aes(x=val_cat,y=prop,fill=val_fill), position="dodge" ) +
  facet_wrap( ~ group )

生产

enter image description here

但是回到您的“无数据操作方法”,我认为您的错误在y变量内。例如,考虑以下代码和输出。

df2 %>%
  ggplot() +
  stat_count( aes(x=val_cat,y=..count..,color=val_fill,label=tapply(..count.., ..x.. , sum)[..x..]),
              geom="text" ) +
  facet_wrap( ~ group )

enter image description here

在上图中,y值是您尝试的比例的分子,label值是您尝试的比例的分母。我认为您需要做的只是弄乱tapply()函数调用,直到获得ylabel的正确组合。

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