2017-01-25 22 views
0

如果重複,請將我指向原始問題。ggplot2相對於特定訂單繪製圖形

我想使用ggplot2在R中畫一個圖,下面的代碼顯示了我想實現的。

require(ggplot2) 
require(data.table) 

set.seed(1) 

dat <- data.table(time = rep(c(1:40), times = 5), 
        value = runif(200), 
        team = rep(c("A","B","C","D","E"), each = 40)) 
dat[, value := value/sum(value), by = .(time)] 

ggplot(dat, aes(x = time, y = value, group=team, fill=team)) + 
geom_area(position = "fill") + 
scale_fill_manual(values = c("red","blue","green","pink","yellow"), 
        breaks = c("D", "B", "E", "A", "C"), 
        labels = c("D", "B", "E", "A", "C")) 

GGPLOT2輸出:

enter image description here

正如你可以看到,圖中的順序不匹配傳奇的順序。它是A,B,C,D,E的順序,但不是D,B,E,A,C。我想要在頂部繪製粉紅色的圖形,然後是藍色,然後是黃色,然後是紅色,然後綠色(DBEAC)。我怎樣才能做到這一點?

在此先感謝!

+0

如果你離開了scale_manual,訂單是相同的。 –

+0

或者,如果訂單由於某種原因很重要。重新排列因子變量。就像'df $ team < - factor(df $ team,levels = c(「D」,「B」,「E」,「A」,「C」))''。然後繪製它。 – lmo

+1

如果您將'breaks'參數設置爲scale_manual,則順序也是您所期望的。我幾乎從不知道這樣的異常是錯誤還是預期的行爲,因爲ggplot2函數的幫助頁面很少告訴我足夠的關於可接受的參數值或其效果的信息。 –

回答

1

這是相當多的ggplot2: Changing the order of stacks on a bar graph重複,

geom_area出現疊加的區域按它們首先出現在數據的順序。

以適當的順序排序dat出現解決您的問題

# create order you want 
my_order <- c("D", "B", "E", "A", "C") 
# reversed to get correct ordering in data table 
dat[, order := match(team, rev(my_order))] 
# sort the data.table 
setorder(dat, time, order) 
# make the plot 
ggplot(dat, aes(x = time, y = value, fill=team))+ 
    geom_area(position = "fill") + 
    scale_fill_manual(values = c("red","blue","green","pink","yellow"), 
        breaks = my_order , 
        labels = my_order) 

enter image description here

+0

我相信你是對的,但在我的機器上,ggplot2仍然提供了相同的結果。 –