如何为两个不同的数据列和一个组列创建条形图

时间:2013-08-15 16:27:21

标签: r ggplot2

我的数据框:

dput(head(x,3))
structure(list(Programs = structure(1:3, .Label = c("400.perlbench", 
"401.bzip2", "403.gcc", "429.mcf", "445.gobmk", "456.hmmer", 
"458.sjeng", "462.libquantum", "464.h264ref", "471.omnetpp", 
"473.astar", "483.xalancbmk"), class = "factor"), Base_Run_Time = c(988.746037, 
1401.357446, 821.134215), Base_Rate = c(790.49624, 550.8944, 
784.28104), Base_Geo_Mean = c(837.6709, 837.6709, 837.6709), 
    Bench_Mark_Run_Time = c(827.236707, 1329.663649, 818.863431
    ), Peak_Rate = c(944.83232, 580.59792, 786.45592), Chip = structure(c(2L, 
    2L, 2L), .Label = c("E5_2660", "E7_4860", "ultrasparc"), class = "factor"), 
    Bench_Geo_Mean = c(790.4498, 790.4498, 790.4498), Percent_Difference = c(0.06, 
    0.06, 0.06)), .Names = c("Programs", "Base_Run_Time", "Base_Rate", 
"Base_Geo_Mean", "Bench_Mark_Run_Time", "Peak_Rate", "Chip", 
"Bench_Geo_Mean", "Percent_Difference"), row.names = c(NA, 3L
), class = "data.frame")

我需要创建一个条形图,其中每个组需要并排使用Base_Run_Time和Bench_Mark_Run_Time,一个是橙色,另一个是蓝色。

我尝试过类似的东西,但这给了我一个堆栈图表。我需要每个Base_Run_Time和Bench_Mark_Run_Time的条形图:

ggplot(x)+geom_bar(data=x, aes(Programs, Base_Run_Time, colour="orange", group=Chip), stat="identity") + geom_bar(data=x, aes(Programs,Bench_Mark_Run_Time, colour="blue", fill="green", group=Chip), stat="identity")

任何想法?

1 个答案:

答案 0 :(得分:3)

您应该将数据从宽格式转换为长格式,然后绘制数据。使用position="dodge",您可以设置条形并排。从融化的数据框中,使用value作为y值,使用variable作为填充。使用scale_fill_manual(),您可以获得所需的颜色。

library(reshape2)
xx <- melt(x, id = "Programs",measure.vars = c("Base_Run_Time", "Bench_Mark_Run_Time"))
       Programs            variable     value
1 400.perlbench       Base_Run_Time  988.7460
2     401.bzip2       Base_Run_Time 1401.3574
3       403.gcc       Base_Run_Time  821.1342
4 400.perlbench Bench_Mark_Run_Time  827.2367
5     401.bzip2 Bench_Mark_Run_Time 1329.6636
6       403.gcc Bench_Mark_Run_Time  818.8634

ggplot(xx,aes(Programs,value,fill=variable))+
  geom_bar(stat="identity",position="dodge")+
  scale_fill_manual(values=c("orange","blue"))

enter image description here