带参考值的ggplot条形图

时间:2014-06-13 08:39:35

标签: r ggplot2 bar-chart

我有一个包含考试成绩的数据框,其中所有子项都被分组到一个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 个答案:

答案 0 :(得分: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命令中的百分比&amp;如何重新排列条形的顺序:

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

答案 1 :(得分: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")