2012-04-18 170 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

謝謝。