正负条形图 | R

就是看见别人文章中有这种图,这种需求还挺常见,画一下吧

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()
并排
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

推荐阅读更多精彩内容