2014-06-13 72 views
0

我有一個數據框包含考試結果,其中所有的subquestions分組爲一個questionCategory,每個類別有一個總分數的分數,和學生的實際分數。ggplot barplot與參考值

>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 

我不能完全弄清楚如何繪製以下數據幀中諸如方式,我可以列出MAX_POINTS和使用ggplot兩間酒吧爲每個類別得分,而是試圖用

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

似乎突出了我對ggplot填充的完全誤解?

enter image description here

我怎麼能代替並排繪製數據框邊的這兩列?

回答

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


編輯:向@皮埃爾的回答變化,這表明,您還可以計算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") 
+0

謝謝皮埃爾和@Jaap,我來到了相同的結論皮埃爾,因爲它同時是最容易實現和解釋 – tschmitty