2017-06-06 126 views
1

奇怪的順序,我試圖創建一個發散堆積條形圖像here,和我遇到了類似的問題,這SO question。我的方法稍有不同,但我通過一個數據集管理它,而不是兩個,而且我的顏色與我的數據無關。ggplot疊置條

Reprex如下:

library(tidyverse) 
library(RColorBrewer) 
x <- tribble(
    ~response, ~count, 
    0,   -27, 
    1,   -9, 
    2,   -41, 
    3,   -43, 
    4,   -58, 
    5,  -120, 
    5,   120, 
    6,   233, 
    7,   379, 
    8,   388, 
    9,   145, 
    10,   61 
) %>% 
    mutate(response = factor(response)) 

ggplot(x, aes(x = 1, y = count, fill = response)) + 
    geom_col() + 
    scale_fill_brewer(palette = "RdBu") + 
    coord_flip() 

這給了我這樣一個形象:enter image description here

的問題是與層疊的數據在零的右側的順序做他們堆疊似乎按降序排列。關於如何解決此問題的任何想法,將不勝感激(預期訂貨會是0-10,不0-5,10-5)

回答

1

一個艱難的一個!我玩的順序,看起來,和geom_col不喜歡它,當你結合正常和負值的常見相同的順序。所以,我分你的數據在數據幀的正值和負值內,產生的顏色爲每個響應的價值和使用的兩個geoms爲正值和負值分別:

library(tidyverse) 
library(RColorBrewer) 
x <- tribble(
    ~response, ~count, 
    0,   -27, 
    1,   -9, 
    2,   -41, 
    3,   -43, 
    4,   -58, 
    5,  -120, 
    5,   120, 
    6,   233, 
    7,   379, 
    8,   388, 
    9,   145, 
    10,   61 
) %>% 
    # Get absolute values and add dummy to distuingish positive and negative values 
    mutate(subzero = count < 0, 
     count = abs(count)) 

# Generate variable with colors from ColorBrewer for every response level (ugly but works) 
colors <- brewer.pal(length(unique(x$response)),"RdBu") 
x$colors <- NA 
for (i in 1:nrow(x)){ 
    x$colors[i] <- colors[x$response[i]+1] 
} 


ggplot() + 
    geom_bar(data = x[x$subzero==T,], aes(x = "", y = -count, fill = reorder(colors, response)), position="stack", stat="identity") + 
    geom_bar(data = x[x$subzero==F,], aes(x = "", y = count, fill = reorder(colors, -response)), position="stack", stat="identity") + 
    geom_hline(yintercept = 0, color =c("black")) + 
    scale_fill_identity("Response", labels = unique(x$response), breaks=unique(x$colors), guide="legend") + 
    coord_flip() + 
    labs(y="",x="") + 
    theme(legend.position = "bottom", legend.direction = "horizontal") + 
    scale_y_continuous(breaks=seq(-1400,1400,200), limits=c(-1400,1400)) 

UPD:由Y型規模的平衡,因此看起來更清晰 enter image description here

1

雖然並不直觀(對我來說),使用:

ggplot(x, aes(x = 1, y = order(count), fill = response)) + 
    geom_col() + 
    scale_fill_brewer(palette = "RdBu",direction=1) + 
    coord_flip() 

它考慮到基於響應排序(而不是爲了(響應))

+0

這是一個棘手的問題,因爲最終這應該類似於一個從0到10的Likert刻度,從左到右。 5中有2條記錄的原因是因爲我希望一半是圖表「中點」的任一側。這種排序不符合目的。 – Dan

+0

啊,是的,後來注意到順序顛倒了(相對於傳說)。此外,這些值代表有序值(而不是實際計數),使其成爲不理想的答案:)或者,您可以根據計數來排序變量,創建一個手動比例,包括'RColorBrewer :: brewer.pal(11,「RdBu」) '(重複5次)並附上你的DF。這可以用作'scale_fill_manual'的輸入。 – timfaber

0

您可以使用position_stack(reverse=TRUE)

ggplot(x, aes(x = 1, y = count, fill = response)) + 
    geom_col(position = position_stack(reverse=TRUE)) + 
    scale_fill_brewer(palette = "RdBu") + 
    coord_flip() 
+0

仍然不能很好地工作,因爲紅色在中間而不是藍色。 – Dan