2017-06-06 66 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