2015-11-11 34 views
0

我有其中數據結構這樣一個CSV文件:如何將數據傳遞到R中的堆疊條形圖?

model,pass,fail 
a,10,5 
b,5,10 
c,15,5 

我想打一個堆積條形圖,將是這樣的: stacked bar chart

我曾嘗試使用下面的代碼(數據是導入的csv文件的名稱):

barplot(as.matrix(data), col=c("light green","light yellow")) 
legend("topright", fill=c("light green","light yellow"), legend=rownames(data)) 

...但是這將標題名稱作爲數據點。我應該如何將「數據」傳遞給barplot函數,以便每個模型(a,b,c)都是條形圖?

(因爲我是新來的R,我寧可不使用像ggplot的庫現在)

+0

'barplot(噸(數據[2:3]),名稱=數據$模型)'BU你真的不應該考慮基礎圖形的墊腳石。 ggplot2基於圖形語法,可幫助您考慮繪製更合乎邏輯的圖形。 – hrbrmstr

+0

謝謝!爲什麼在[,2:3]中有一個逗號? – kormak

+0

沒有行過濾需要,只選擇2個數據列 – hrbrmstr

回答

0
> model <- c("a", "b", "c") 
> pass <- c(10, 5, 15) 
> fail <- c(5, 10, 5) 
> dat <- data.frame(model, pass, fail) 
> 
> library(ggplot2) 
> library(reshape2) 
> dat <- melt(dat) 
Using model as id variables 
> dat 
    model variable value 
1  a  pass 10 
2  b  pass  5 
3  c  pass 15 
4  a  fail  5 
5  b  fail 10 
6  c  fail  5 
> ggplot(dat, aes(x = model, y = value, fill = variable)) + geom_bar(stat = "identity") 

enter image description here

如果你不想使用GGPLOT2包,就可嘗試

model <- c("a", "b", "c") 
pass <- c(10, 5, 15) 
fail <- c(5, 10, 5) 
dat <- data.frame(pass, fail) 
dat <- t(dat) 
rownames(dat) <- model 

barplot(dat, xlab = "Model", col = c("light green","light yellow")) 
legend("top", legend = rownames(dat), fill = c("light green", "light yellow")) 

enter image description here

+0

_「...我寧願現在不使用任何庫像ggplot」_ – hrbrmstr

相關問題