2012-04-18 159 views
5

多列数据的分组栏积我有以下数据创建中的R

 Input Rtime Rcost Rsolutions Btime Bcost 
1 12 proc.  1 36  614425  40 36 
2 15 proc.  1 51  534037  50 51 
3 18-proc  5 62 1843820  66 66 
4 20-proc  4 68 1645581 104400 73 
5 20-proc(l)  4 64 1658509 14400 65 
6 21-proc 10 78 3923623 453600 82 

我想创建从该数据分组条形图,使得x轴包含Input字段(如基团)而y轴表示Rtime和Btime字段(两个条)的对数刻度。

所有的解决方案/例子我在网上查了放入三个栏布局类似的数据。我不知道如何使用我必须生成分组条形图的数据。或者,如果有此数据转换的方式(手动转换不是一个选项,因为它是一个有很多行的一个巨大的文件)到[Rggplot兼容的数据格式。

编辑:

图形生成使用gncs解决方案

enter image description here

回答

17

按照要求,一个GGPLOT2解决方案:

df <- read.table(text = "  Input Rtime Rcost Rsolutions Btime Bcost 
1 12-proc.  1 36  614425  40 36 
2 15-proc.  1 51  534037  50 51 
3 18-proc  5 62 1843820  66 66 
4 20-proc  4 68 1645581 104400 73 
5 20-proc(l)  4 64 1658509 14400 65 
6 21-proc 10 78 3923623 453600 82",header = TRUE,sep = "") 

dfm <- melt(df[,c('Input','Rtime','Btime')],id.vars = 1) 

ggplot(dfm,aes(x = Input,y = value)) + 
    geom_bar(aes(fill = variable),stat = "identity",position = "dodge") + 
    scale_y_log10() 

enter image description here

注意风格区别就在这里,在这里,因为log(1) = 0GGPLOT2对待,作为零高度的酒吧和没有按” t绘制任何东西,而barplot绘制一个小存根(在我看来这有点误导)。

+1

真棒。我希望我写愚蠢的Python脚本之前就知道这个{Python是好的,但!}非常感谢joran – Ankit 2012-04-18 19:32:47

+2

值得关注的是'melt'是包'reshape2' – Serenthia 2016-07-08 15:36:41

+0

此外,添加'STAT =“身份”'到需要'geom_bar',因为它默认为'stat =“bin”' – Serenthia 2016-07-08 15:39:37

5

我想我明白这个问题,这是我要建议的(短期 - 选项):

data <- read.table("data.txt", header=TRUE) 
subset <- t(data.frame(data$Rtime, data$Btime)) 
barplot(subset, legend = c("Rtime", "Btime"), names.arg=data$Input, log="y", beside=TRUE) 

这就是你想要的吗?这有点肮脏,但它能完成这项工作。

更新:代码更正。

+0

你是男人!非常感谢。此外,你知道如何使用ggplot做到这一点? – Ankit 2012-04-18 15:53:00

2

joran的回答对我帮助很大,但我不得不使用STAT = “身份”在那样的ggplot声明:

ggplot(dfm, aes(x = Input,y = value)) + 
geom_bar(aes(fill = variable), position = "dodge", stat="identity") + 
scale_y_log10() 

我的R版本3.2.2是与GGPLOT2 1.0版本。 1

谢谢。