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

raf*_*ira 3 r ggplot2

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

在此处输入图片说明

数据可重复的例子

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()
Run Code Online (Sandbox Code Playgroud)

Axe*_*man 6

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

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

在此处输入图片说明

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

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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明