首页 文章

按ggplot2()中的因子级别分组

提问于
浏览
1

我有一个包含四个三级分类变量的数据框:before_weight,after_weight,before_pain和after_pain .

我想制作一个条形图,其中包含各级变量的比例 . 我目前的代码实现了 .

问题在于数据的呈现 . 我希望将相应的前后条组合在一起,以便表示在before_weight变量中回答1的人的条被分组到代表在after_weight变量中回答1的人的条旁边,依此类推重量和疼痛变量 .

我一直在尝试使用dplyr,mutate()和许多ifelse()语句来创建一个新的变量来配对有问题的组,但似乎无法让它工作 .

任何帮助将非常感激 .

起点(df):

df <- data.frame(before_weight=c(1,2,3,2,1),before_pain=c(2,2,1,3,1),after_weight=c(1,3,3,2,3),after_pain=c(1,1,2,3,1))

当前代码:

library(tidyr)
dflong <- gather(df, varname, score, before_weight:after_pain, factor_key=TRUE)
df$score<- as.factor(df$score)
library(ggplot2)
library(dplyr)
dflong %>%
  group_by(varname) %>%
  count(score) %>%
  mutate(prop = 100*(n / sum(n)))  %>%
  ggplot(aes(x = varname, y = prop, fill = factor(score))) +  scale_fill_brewer() + geom_col(position = 'dodge', colour = 'black')

UPDATE:

我想要比例而不是数量,所以我试图调整Nate的代码 . 由于我使用问题变量对数据进行分组以获得比例,我似乎无法使用gsub()来更改该变量的内容 . 相反,我添加了question2并将其传递给facet_wrap() . 它似乎工作:

df %>% gather("question", "val") %>% 
   count(question, val) %>%
   group_by(question) %>%
   mutate(percent = 100*(n / sum(n))) %>%
   mutate(time= factor(ifelse(grepl("before", question), "before", "after"), c("before", "after"))) %>%
   mutate(question2= ifelse(grepl("weight", question), "weight", "pain"))  %>%
   ggplot(aes(x=val, y=percent, fill = time)) + geom_col(position = "dodge") + facet_wrap(~question2)

1 回答

  • 0

    这段代码是否会使您进行视觉比较?一个 ifelse 和一个 gsub 将有助于创建我们可以用于分割和填充 ggplot 的变量 .

    df %>% gather("question", "val") %>% # go long
        mutate(time = factor(ifelse(grepl("before", question), "before", "after"),
                         c("before", "after")), # use factor with levels to control order
               question = gsub(".*_", "", question)) %>% # clean for facets
        ggplot(aes(x = val, fill = time)) + # use fill not color for whole bar
        geom_bar(position = "dodge") + # stacking is the default option
        facet_wrap(~question) # two panels
    

    enter image description here

相关问题