就是看见别人文章中有这种图,这种需求还挺常见,画一下吧
library(ggplot2)
a <- mtcars
# 首先随机生成负值
setseed(123) # 设定种子,保证可重复
index <- sample(seq(1,32), 20) # 随机取20个index
a$wt[index] <- a$wt[index] * -1 # 修改为负值
# 堆叠
ggplot(a, aes(x = factor(carb), y = wt, fill = factor(gear))) +
geom_bar(stat = "identity") +
geom_hline(yintercept = 0) +
coord_flip() +
scale_fill_brewer(palette = "Paired") +
labs(fill = "gear") + # 修改图例标题
theme_classic()
堆叠
# 百分比
ggplot(a, aes(x = factor(carb), y = wt, fill = factor(gear))) +
geom_bar(stat = "identity", position = "fill") +
geom_hline(yintercept = 0) +
coord_flip() +
scale_fill_brewer(palette = "Paired") +
labs(fill = "gear") + # 修改图例标题
theme_classic()
百分比
# 并排
ggplot(a, aes(x = factor(carb), y = wt, fill = factor(gear))) +
geom_bar(stat = "identity", position = "dodge") +
geom_hline(yintercept = 0) +
coord_flip() +
scale_fill_brewer(palette = "Paired") +
labs(fill = "gear") + # 修改图例标题
theme_classic()
并排