【问题标题】:Create multiple 2-column bar plots plotting a particular factor against all factors in a loop创建多个 2 列条形图,针对循环中的所有因子绘制特定因子
【发布时间】:2018-03-13 02:06:09
【问题描述】:

我有一个包含 4 列的数据框。第一列、第二列、第三列和第四列分别详细说明了不同的位置(因素)、成功次数、尝试次数和成功百分比(第二列/第三列 * 100)。

数据如下所示:

location <- c("a", "b", "c", "d", "e")
success <- c(12, 40, 30, 10, 20)
attempts <- c(20, 54, 32, 12, 26)
perc_success <- c(60, 74, 94, 83, 76)
df <- as.data.frame(cbind(location, success, attempts, perc_success))

我想循环创建多个 2 列条形图,绘制特定位置的成功百分比与所有位置的平均成功百分比。

意思是,我想要一个有 2 列的条形图,x 轴由位置“A”和位置“所有位置”组成,y 轴显示位置“A”和位置“的成功百分比所有地点。”

我想循环上面的相同过程并创建另一个条形图,绘制位置 B 与所有位置、位置 C 与所有位置等。

我现在正在做的是在将 Excel 数据导入 R 之前手动计算“所有位置”行,然后根据所有位置手动绘制每个位置。

请参阅下面的链接以获取我正在寻找的所需输出(在本例中,位置 A 与所有位置相对)。

提前致谢!

Barplot Example: Location A against all Locations

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:
    library(ggplot2)
    
    location <- c("a", "b", "c", "d", "e")
    success <- c(12, 40, 30, 10, 20)
    attempts <- c(20, 54, 32, 12, 26)
    perc_success <- c(60, 74, 94, 83, 76)
    df <- as.data.frame(cbind(location, success, attempts, perc_success))
    
    #Calculate average value
    avg <- mean(perc_success)
    
    #Create list to store plots in
    plotvec<-vector("list",length=5)
    
    for(i in c(1:5)){
      #Create a burner data frame with only the relevant data
      burner <- data.frame(c(paste(location[i]),"avg"),c(perc_success[i],avg))
      names(burner) <- c("location","perc_success")
    
      #Create a plot from that buner data frame
      plot <- ggplot(data=burner,aes(y=perc_success,x=location)) +
        geom_bar(stat="identity")
    
      #Store plot in list
      plotvec[[i]]<-plot
    }
    
    #Display all plots
    plotvec
    

    这有帮助吗?如有任何问题,请随时回复。

    【讨论】:

    • 谢谢!有效。只是好奇,我有两个问题。首先,c(paste(location[i]), "avg") 中的 "avg" 是什么意思?为什么有“平均值”和平均值?其次,是否可以使用 apply 函数来做同样的事情?再次感谢!
    • @DTYK 好问题! “avg”在那里,因此当您创建绘图时,它会正确标记列。不带引号的 avg 调用存储数字的变量。我确定你可以使用 apply 语句,但我不太擅长这些,所以我无法告诉你如何使用。
    • 感谢您的帮助!非常感激。干杯!
    猜你喜欢
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多