用ggplot2绘制发散堆积的条形图

问题描述:

有没有一种方法可以使用ggplot2来创建不同的堆叠条形图,如下面图像的右图所示?

Is there a way to use ggplot2 to create divergent stacked bar charts like the one on the right-hand side of the image below?

library(ggplot2)
library(scales)
library(reshape)

dat <- read.table(text = "    ONE TWO THREE
                  1   23  234 324
                  2   34  534 12
                  3   56  324 124
                  4   34  234 124
                  5   123 534 654",sep = "",header = TRUE)

# reshape data
datm <- melt(cbind(dat, ind = rownames(dat)), id.vars = c('ind'))

# plot
ggplot(datm,aes(x = variable, y = value,fill = ind)) + 
  geom_bar(position = "fill",stat = "identity") +
  coord_flip()

当然,正值堆叠为正,负值堆叠为负.不要使用位置fill.只需将所需的值定义为负值,然后使它们实际上为负值即可.您的示例仅具有正面得分.例如

Sure, positive values stack positively, negative values stack negatively. Don't use position fill. Just define what you want as negative values, and actually make them negative. Your example only has positive scores. E.g.

ggplot(datm, aes(x = variable, y = ifelse(ind %in% 1:2, -value, value), fill = ind)) + 
    geom_col() +
    coord_flip()

如果您还想缩放到1,则需要进行一些预处理:

If you want to also scale to 1, you need some preprocessing:

library(dplyr)
datm %>% 
  group_by(variable) %>% 
  mutate(value = value / sum(value)) %>% 
  ggplot(aes(x = variable, y = ifelse(ind %in% 1:2, -value, value), fill = ind)) + 
  geom_col() +
  coord_flip()