#加载函数包
library(ggplot2)
library(hrbrthemes)
#构建数据
data <- data.frame(
group=c("A ","B ","C ","D ") ,
value=c(33,62,56,67) ,
number_of_obs=c(150,500,400,200)
)
#查看数据
data
#计算每一个柱子的左右边界
data$right <- cumsum(data$number_of_obs) + 30*c(0:(nrow(data)-1)) #将一个数据集中的每个观察值(number_of_obs)向右移动(宽度累加+间隔累加)
data$left <- data$right - data$number_of_obs
#再次查看数据
data
#画图
ggplot(data, aes(ymin = 0)) +
geom_rect(aes(xmin = left,
xmax = right,
ymax = value,
colour = group,
fill = group)) +
xlab("number of obs") +
ylab("value") +
theme_ipsum() +
theme(legend.position="none")