首页 文章

带参考值的ggplot条形图

提问于
浏览
0

我有一个包含考试结果的数据框,其中所有子项都被分组到一个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填充的完全误解?

enter image description here

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

2 回答

  • 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()
    

    给出:
    enter image description here


    编辑:@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()
    

    给出:
    enter image description here

  • 0

    为了便于阅读您的数据,我建议仅绘制分数百分比 .

    enter image description here

    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")
    

相关问题