【问题标题】:Create combined bar plot of multiple variables using ggplot使用 ggplot 创建多个变量的组合条形图
【发布时间】:2020-04-24 16:02:04
【问题描述】:

我正在尝试使用以下数据创建频率(% terms)条形图:

>fulldata
Type Category
Sal         0
Sal         0
Sal         1
Sal         0
Sal         1
Sal         1
Self        1
Self        0
Self        1
Self        0
Self        0

所以,我正在尝试创建一个条形图(使用 ggplot),它同时显示完整数据中 SalSelf 的百分比以及 Category==1SalSelf 的百分比侧(带有 % 值的标签)。 我尝试通过从完整数据中过滤Category==1 创建一个单独的数据框,但它们彼此重叠。我尝试了以下方法:

> Category1 = fulldata[which(fulldata$Category==1),]

ggplot(fulldata, aes(x=Type,y = (..count..)/sum(..count..)))+
    geom_bar()+
    geom_label(stat = "count", aes(label=round(..count../sum(..count..),3)*100), 
               vjust=1.2,size=3, format_string='{:.1f}%')+
    scale_y_continuous(labels = scales::percent)+
    labs(x = "Type", y="Percentage")+
    geom_bar(data = Category1, position = "dodge", color = "red")

*原始数据大约有 80000 行。

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    一种可能的解决方案是从计算ggplot2 之外的所有比例开始。

    这里是一个假的例子:

    df <- data.frame(Type = sample(c("Sal","Self"),100, replace = TRUE),
                     Category = sample(c(0,1),100, replace = TRUE))
    

    我们可以如下计算每个比例以获得最终的数据帧:

    library(tidyr)
    library(dplyr)
    
    df %>% group_by(Category, Type) %>% count() %>% 
      pivot_wider(names_from = Category, values_from = n) %>%
      mutate(Total = `0`+ `1`) %>%
      pivot_longer(-Type, names_to = "Category", values_to = "n") %>%
      group_by(Category) %>%
      mutate(Percent = n / sum(n))
    
    # A tibble: 6 x 4
    # Groups:   Category [3]
      Type  Category     n Percent
      <fct> <chr>    <int>   <dbl>
    1 Sal   0           27   0.458
    2 Sal   1           22   0.537
    3 Sal   Total       49   0.49 
    4 Self  0           32   0.542
    5 Self  1           19   0.463
    6 Self  Total       51   0.51 
    

    然后,如果您有 ggplot2 的序列,您可以在一个序列中获得 barg raph:

    df %>% group_by(Category, Type) %>% count() %>% 
      pivot_wider(names_from = Category, values_from = n) %>%
      mutate(Total = `0`+ `1`) %>%
      pivot_longer(-Type, names_to = "Category", values_to = "n") %>%
      group_by(Category) %>%
      mutate(Percent = n / sum(n)) %>%
      ggplot(aes(x = reorder(Category, desc(Category)), y = Percent, fill = Type))+
      geom_col()+
      geom_text(aes(label = scales::percent(Percent)), position = position_stack(0.5))+
      scale_y_continuous(labels = scales::percent)+
      labs(y = "Percentage", x = "Category")
    

    它回答了你的问题吗?

    【讨论】:

    • 有什么方法可以直接使用 ggplot 而不是创建一个新的频率表,因为我有很多变量?
    • ggplot2 中做到这一点真的很困难,因为你要计算类别和计算所有内容,这非常棘手。我编辑了我的答案,向您展示如何在单个管道序列中执行此操作,而无需计算各种类别。让我知道是否可以。
    • 我收到此错误:``` 错误:此 tidyselect 接口尚不支持谓词。```
    • 我从未见过这个错误。你用的是什么版本的tidyverseRRstudio?你试过我提供的例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 1970-01-01
    相关资源
    最近更新 更多