【问题标题】:Using apply and ggplot to make multiple bar charts in R使用 apply 和 ggplot 在 R 中制作多个条形图
【发布时间】:2021-08-02 18:48:40
【问题描述】:

我有来自调查的数据(1300 行和 12 列),我想为所有列制作条形图(我已删除所有 NA 值)。

q1 <- rep(c("yes", "no"), 10)
q2 <- rep(c("no", "yes"), 10)
q3 <- 20:39
data <- cbind.data.frame(q1,q2,q3)```

我正在使用以下代码,但我似乎无法为 x 轴获得正确的标签(应该只是列名)。

lapply(data[,c(1:3)], function(variable) ggplot(data = data,
                                     mapping = aes(variable)) + 
         geom_bar() + labs(x = variable, y = "count"))

【问题讨论】:

    标签: r ggplot2 dplyr apply


    【解决方案1】:

    实现所需结果的一种选择是循环变量名称并使用来自rlang.data 代词,如下所示:

    q1 <- rep(c("yes", "no"), 10)
    q2 <- rep(c("no", "yes"), 10)
    q3 <- 20:39
    data <- data.frame(q1, q2, q3)
    
    library(ggplot2)
    
    lapply(names(data), function(variable) {
      ggplot(
        data = data,
        mapping = aes(.data[[variable]])
      ) +
        geom_bar() +
        labs(x = variable, y = "count")
    })
    #> [[1]]
    

    #> 
    #> [[2]]
    

    #> 
    #> [[3]]
    

    【讨论】:

      【解决方案2】:

      base R 中,使用barplottable

      par(mfrow = c(3, 1))
      Map(\(x, y) barplot(table(x), xlab = y), data, names(data))
      

      -输出

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-02
        • 1970-01-01
        • 1970-01-01
        • 2022-11-23
        相关资源
        最近更新 更多