0
votes

I have a data frame containing exam results where all subquestions are grouped into a questionCategory, and each category has an total point score, and the students actual score.

>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

I can't quite figure out how to plot the following dataframe in such as way that I can list the max_points and score as two bars for each category using ggplot, but trying to use

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

seems to highlight my complete misunderstanding of ggplot's fill?

enter image description here

How can I instead plot these two columns of the dataframe side by side?

2

2 Answers

1
votes

When you reshape your dataframe into long format, you can get the desired result:

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

which gives: enter image description here


Edit: A variation to @Pierre's answer which shows that you can also calculate the percentage inside the ggplot command & how you can rearrange the order of the bars:

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

which gives: enter image description here

0
votes

To facilitate the reading of your data, I suggest to plot only score percentage.

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