【问题标题】:ggplot barplot with references values带有参考值的ggplot barplot
【发布时间】:2014-06-13 08:39:34
【问题描述】:

我有一个包含考试结果的数据框,其中所有子问题都被分组到一个 questionCategory 中,每个类别都有总分和学生的实际分数。

>exam_results 

  questionCategory max_points  score
1          Analysis         5  0.000
2           Design         18  5.940
3   Implementation          8  4.000
4     Requirements         37 23.786
5              UML         17  7.000
6               UP         15  4.250

我不太清楚如何绘制以下数据框,以便我可以使用 ggplot 将 max_points 和得分列为每个类别的两个条形,但尝试使用

ggplot(data=exam_results, aes(x=questionCategory,y=score)) + geom_bar(aes(fill=max_points),stat="identity")

似乎突出了我对 ggplot 填充的完全误解?

我怎样才能并排绘制数据框的这两列?

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    当您将数据框重塑为长格式时,您可以获得所需的结果:

    require(reshape2)
    exam <- melt(exam_results, id="questionCategory")
    
    require(ggplot2)
    ggplot(exam, aes(x=questionCategory, y=value, fill=variable)) +
      geom_bar(stat="identity", position="dodge") +
      scale_fill_discrete("Legend title", labels=c("Maximum score","Actual score")) +
      theme_bw()
    

    给出:


    编辑:@Pierre 答案的变体,它表明您还可以计算 ggplot 命令中的百分比以及如何重新排列条形的顺序:

    exam_results$xlabels <- paste0(exam_results$questionCategory," (",exam_results$max_points,")")
    
    ggplot(exam_results, aes(x=reorder(xlabels,score/max_points), y=100*score/max_points)) +
      geom_bar(stat="identity", fill="grey80", color="red", width=0.7) +
      xlab("Questioncategory (maximum points)\n") +
      ylab("Percentage score") +
      coord_flip() +
      theme_bw()
    

    给出:

    【讨论】:

      【解决方案2】:

      为了方便阅读您的数据,我建议只绘制分数百分比。

      exam_results$pct_score=with(exam_results,100*score/max_points)
      exam_results$questionCategory_max_points=with(exam_results,paste(questionCategory," (",max_points,")",sep=""))
      
      require(ggplot2)
      ggplot(exam_results,aes(questionCategory_max_points,pct_score))+
        geom_bar(fill="grey50")+
        coord_flip()+theme_bw()+
        xlab("Question Category\n(maximum score)")+
        ylab("Score in percentage")
      

      【讨论】:

      • 谢谢 Pierre 和 @Jaap,我得出了与 Pierre 相同的结论,因为它同时是最容易实现和解释的
      猜你喜欢
      • 2013-10-23
      • 2022-12-16
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      相关资源
      最近更新 更多