2015-09-30 132 views
1

我有這個數據幀:分組條形圖,[R

TotalCost Vehicles Bikes 
    92  1  2 
    92  1  3 
    96  1  6 
    93  2  2 
    93  2  3 
    95  2  6 
    108  3  2 
    108  3  3 
    108  3  6 

我想與填充「自行車」參數欄繪製,但這個命令:

ggplot(data, aes(Vehicles, TotalCost)) + geom_bar(aes(fill = Bikes), position = "dodge", stat="identity") 

給我這個情節,沒有任何顏色 enter image description here

我在做什麼錯?

回答

0
library("magrittr") 
library("reshape2") 
library("ggplot2") 

rawdata = matrix(data = strsplit(split = ",", "92,1,2,92,1,3,96,1,6,93,2,2,93,2,3,95,2,6,108,3,2,108,3,3,108,3,6") %>% unlist %>% as.numeric, 
     ncol = 3, byrow = T) 
colnames(rawdata) = c("TotalCost","Vehicles","Bikes") 
df = as.data.frame(rawdata, stringsAsFactors = F) 

如果你的 「自行車」 的數據是連續的,那麼你可以尋找以下:

ggplot(df, aes(x = Vehicles, y = TotalCost)) + geom_bar(aes(fill = Bikes), stat="identity") 

enter image description here

如果自行車」被更多不同的類別,那麼以下可能是它:

ggplot(DF,AES(X =車輛,Y = TOTALCOST))+ geom_bar(AES(填充= as.factor(自行車)),STAT = 「同一性」,位置= 「躲閃」)

enter image description here

0

發生這種情況是因爲您無法基於數字量躲避,因爲它是連續的。如果你指定fill=factor(Bikes)它會做正確的事情;否則ggplot不知道如何「閃避」連續值。

或者,您也可以通過添加group=Bikes到美學的主情節或geom_bar明確指定分組,:

ggplot(df, aes(x=Vehicles, y=TotalCost)) + 
    geom_bar(aes(fill=Bikes, group=Bikes), position="dodge", stat="identity") 

factor方法的優點是,每個酒吧都有自己的標籤,你可以使用離散色階(如布魯爾)來使分化清晰。

隨着group方法中,着色將反映的相對值,這可能是可取的,但也可以使積硬如果存在用於bikes多個值來讀取,由於比較相鄰Vehicles列將涉及比較微妙灰度。如果我們在108, 3, 7附加另一行,則很難比較23分組。

ggplot(rbind(df, c(108, 3, 7)), aes(x=Vehicles, y=TotalCost)) + 
    geom_bar(aes(fill=Bikes, group=Bikes), position="dodge", stat="identity") 

enter image description here

+0

那麼我該如何繪製數據框?或者我如何更改數據框以繪製分組欄? – slash89mf