如何在R中分组barchart中产生堆叠条

编程入门 行业动态 更新时间:2024-10-19 00:28:38
本文介绍了如何在R中分组barchart中产生堆叠条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下图表

test <- data.frame(person=c("A", "B", "C", "D", "E"), value1=c(100,150,120,80,150), value2=c(25,30,45,30,30) , value3=c(100,120,150,150,200))

我想为每个人绘制一个分组barchart其中一个条表示value1,另一个条是value2和value3的堆叠。有没有办法,我可以使用ggplot2做到这一点?我可以使用facet来绘制这些单独的图形一个在另一个之下吗?

I want to plot a grouped barchart (horizontal) for each person where one bar indicates value1 and the other bar is stack of value2 and value3. Is there a way with which I can do this using ggplot2? Can I use facets to plot these individual graphs one below the other?

推荐答案

这里是我想出来的,类似这里提出的解决方案:组合条形图中的堆叠条

Here is what I came up with, similar to a solution proposed here: stacked bars within grouped bar chart

  • Melt data.frame 并添加新列 cat library(reshape2) # for melt melted <- melt(test, "person") melted$cat <- '' melted[melted$variable == 'value1',]$cat <- "first" melted[melted$variable != 'value1',]$cat <- "second"

  • 绘制一个堆叠图表 cat vs value ,由 person 您可能需要调整标签以获得所需的内容:

  • Plot a stacked chart cat vs value, faceting by person. You may need to adjust the labels to get what you want:

    ggplot(melted, aes(x = cat, y = value, fill = variable)) + geom_bar(stat = 'identity', position = 'stack') + facet_grid(~ person)

    / li>

  • 更多推荐

    如何在R中分组barchart中产生堆叠条

    本文发布于:2023-11-02 17:11:52,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1552957.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:如何在   barchart

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!