2015-06-20 140 views
1

我是R的新手,我正嘗試創建一個簡單的barplot。我已經能夠創建具有正確值的barplot,但所有條形圖只有一種顏色。如果我稍微更改代碼(使用table()而不是as.table()),我會得到錯誤的值,但圖表上的顏色是正確的。我怎樣才能讓as.table()在圖中接受多種顏色?下面是我的代碼的修改過的版本:R-Project Barplot顏色

a=30 
b=20 
c=10 
d=15 
x=matrix(c(a,b,c,d),ncol=4,byrow=TRUE) 
colnames(x)=c("Label1","Label2","Label3","Label4") 
    rownames(x)=c("Percentage") 
    x=as.table(x) 
    color=c("red","blue","green","orange") 
barplot(x,main="X",ylab="Percent",cex.names=0.75,col=color) 

回答

1

的載體,而不是一個表傳遞應該做的伎倆:

barplot(x[1, ], main="X", ylab="Percent", cex.names=0.75, col=color) 

或者

barplot(x["Percentage", ], main="X",ylab="Percent",cex.names=0.75, col=color) 

enter image description here

+0

多虧了你們兩個!這解決了一個非常令人沮喪和看似簡單的困境。 – David

2

使用beside = TRUE參數:

barplot(x, beside = TRUE, main="X", ylab="Percent", cex.names=0.75, col=color) 

enter image description here