Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R ggplot带参考值的条形图_R_Ggplot2_Bar Chart - Fatal编程技术网

R ggplot带参考值的条形图

R ggplot带参考值的条形图,r,ggplot2,bar-chart,R,Ggplot2,Bar Chart,我有一个包含考试结果的数据框架,其中所有子问题都被分组到一个问题类别中,每个类别都有一个总分和学生的实际分数 >exam_results questionCategory max_points score 1 Analysis 5 0.000 2 Design 18 5.940 3 Implementation 8 4.000 4 Requirements 3

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

>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_点和分数列为两个条,但是尝试使用

ggplot(data=exam_results, aes(x=questionCategory,y=score)) + geom_bar(aes(fill=max_points),stat="identity")
似乎突出了我对ggplot填充的完全误解


我怎样才能将数据帧的这两列并排绘制呢

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

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()
其中:

为了便于阅读数据,我建议只绘制分数百分比

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相同的结论,因为它同时是最容易实现和解释的
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")