【问题标题】:Using ggplot to create a histogram or barplot of a dataset with separate one-hot encoded columns使用 ggplot 创建具有单独的 one-hot 编码列的数据集的直方图或条形图
【发布时间】:2021-07-28 18:33:17
【问题描述】:

好的,我有一个包含两个分类变量的数据集,我想将它们绘制在直方图或条形图上。我想这样做以验证我的怀疑,即这两个类别的比例不相等。这是关键,因为我正在尝试开发一个分类器,并且我需要知道类别的不成比例,以便决定是使用欠采样还是过采样方法(或两者的某种组合)。

表格看起来像这样:

ID Category1 Category2
0 1 0
1 0 0
2 1 0
3 1 0
4 1 0
5 0 1

...等几千行。

显然,我不能按原样将一堆 ggplot 函数菊花链到此,因为对于直方图或条形图,我只能直接指定一列。我尝试过使用gather(),但我认为我不明白它的键值概念是如何工作的,以及如何使用它来将列压缩在一起。即使我可以,它也只会产生一堆 1 和 0,这并不能直接计算为类别的准确表示,因为实际上有许多样本既不存在类别 1 也不存在类别 2,从而有效地给了我一个类别3 代表“未知”。

如何获取这两列并得出一个单独的列来告诉我每个样本是类别 1、类别 2 还是类别 3(未知),以便我可以使用 ggplot 进行绘制?

【问题讨论】:

    标签: r ggplot2 dplyr tidyr


    【解决方案1】:

    我不确定以下内容是否接近问题的要求。

    library(dplyr)
    library(tidyr)
    library(ggplot2)
    
    df1 %>% 
      pivot_longer(-ID) %>%
      mutate(value = factor(value)) %>%
      ggplot(aes(name, fill = value)) +
      geom_bar()
    

    数据

    df1 <-
    structure(list(ID = 0:5, Category1 = c(1L, 0L, 1L, 1L, 1L, 0L
    ), Category2 = c(0L, 0L, 0L, 0L, 0L, 1L)), class = "data.frame", 
    row.names = c(NA, -6L))
    

    【讨论】:

      【解决方案2】:

      我们可以先使用pivot_longer 以正确的格式获取数据:

      library(tidyverse)
      
      df1 <- df %>% 
          pivot_longer(
              cols = starts_with("Cat"),
              names_to = "Category",
              values_to = "values"
          ) 
      
      ggplot(df1, aes(x=factor(Category), fill=factor(values))) +
          geom_bar(position = "dodge")
      

      数据:

      
      df <- tibble(ID = c(0, 1, 2, 3, 4, 5), 
             Category1 = c(1, 0, 1, 1, 1, 0), 
             Category2 = c(0, 0, 0, 0, 0, 1))
      

      【讨论】:

      • 我在设置参数position = "dodge" 时犹豫不决,没有任何特殊原因。点赞。
      【解决方案3】:

      感谢大家的回复。直到现在我才意识到已经添加了 pivot_longer() 作为一种可能的工具,所以这提供了非常丰富的信息。

      最终,我意识到,如果我将其编码为 Python 中每一行的 for 循环,我的“惰性解决方案”将是使用 ifelse() 语句。然后我有一个想法:如果我只是将 mutate() 与 R 的 ifelse() 结合使用而不是使用 gather() 或 pivot_longer() 来获得想要的结果呢?

      ggplot(data = 
          my_df %>% 
          select(Category1, Category2) %>% 
          mutate(METHOD = ifelse(Category1 == 1, "Category1",
              ifelse(Category2 == 1, "Category2", "NONE"))),
          aes(x = METHOD, fill = METHOD)
      ) + 
          geom_bar() 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-12
        • 2018-03-29
        • 2017-08-31
        • 2019-10-27
        • 2018-03-24
        • 2021-11-02
        • 1970-01-01
        相关资源
        最近更新 更多