有没有一种方法可以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)
当然,正值堆叠为正,负值堆叠为负。不要使用位置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)