用ggplot2绘制发散堆积的条形图 [英] Plot divergent stacked bar chart with ggplot2

查看:131
本文介绍了用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()

这篇关于用ggplot2绘制发散堆积的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆