【问题标题】:Multiple variables in one bar plot in RR中的一个条形图中的多个变量
【发布时间】:2021-03-02 15:51:24
【问题描述】:

我的数据结构类似于以下数据:

a <- c(sample(c(0,1), replace=TRUE, size=10))
b <- c(sample(c(0,1), replace=TRUE, size=10))
c <- c(sample(c(0,1), replace=TRUE, size=10))
d <- c(sample(c(0,1), replace=TRUE, size=10))
e <- c(sample(c(0,1), replace=TRUE, size=10))
f <- c(sample(c(0,1), replace=TRUE, size=10))
df <- data.frame(a,b,c,d,e,f)

我现在想在一个条形图中绘制数据,以便为每个变量显示 0 和 1 的数量。任何帮助将不胜感激!

【问题讨论】:

    标签: r variables bar-chart


    【解决方案1】:

    您还可以将数据集转换为长格式并使用新数据集创建绘图:

    library(tidyverse)
    
    df %>%
      pivot_longer(cols = everything()) %>%
      ggplot() +
      geom_bar(aes(x = name,  
                   fill = factor(value))) +
      labs(fill = "Group")
    

    如果您想将条形显示在彼此旁边,您可以将位置设置为dodge

    df %>%
      pivot_longer(cols = everything()) %>%
      ggplot() +
      geom_bar(aes(x = name,  
                   fill = factor(value)),
               position  = "dodge") +
      labs(fill = "Group")
    
    

    【讨论】:

      【解决方案2】:

      如果我理解正确,您只需要获取一列元素的总和并将其绘制成条形图。

      解决办法如下:

      # barplot of the number of 1
      barplot(colSums(df))
      
      # barplot of the number of 0
      barplot(nrow(df) - colSums(df))
      
      # combined plot with stacked bars
      barplot(rbind(colSums(df),nrow(df) - colSums(df))) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        • 2020-09-18
        • 1970-01-01
        • 2011-10-05
        • 1970-01-01
        相关资源
        最近更新 更多