简体   繁体   English

如何从两个数据框创建堆叠和分组条形图?

[英]How to create a stacked and grouped bar chart from two data frames?

I have a stacked barchart that looks like this .我有一个看起来像这样的堆叠条形图。

If I have a second dataframe that has the same layout as the one that created the plot, and I want to group both datasets by position while still keeping the stacked percentages, how would I go about this.如果我有第二个数据框,其布局与创建绘图的数据框布局相同,并且我想按位置对两个数据集进行分组,同时仍保持堆叠百分比,我将如何处理。 I'm not sure how to do it in ggplot2我不知道如何在 ggplot2 中做到这一点

Hard to say without seeing the data and without more information about what you actually want to achieve, but the general approach I would use is to say combine your dataframes - especially if the variables are the same.很难说没有看到数据并且没有关于您实际想要实现的目标的更多信息,但我会使用的一般方法是组合您的数据框- 特别是如果变量相同。 You just want to make sure to maintain "where" each dataset originated, and that will be your identifying column.您只想确保维护每个数据集的“来源”,这将是您的标识列。

So, if your data is in myData1 and myData2 :因此,如果您的数据在myData1myData2

# add identifying columns
myData1$id <- 'dataset1'
myData2$id <- 'dataset2'

# put them together
newData <- rbind(myData1, myData2)

You are not clear on what you're looking for in the combined plot, so you can go about that any number of ways (depending on what you want to do).您不清楚要在组合图中寻找什么,因此您可以通过多种方式进行处理(取决于您想要做什么)。 Maybe the simplest example would be to use facet_grid() or facet_wrap() from ggplot2 to show them in side-by-side plots:也许最简单的例子是使用facet_grid()facet_wrap()ggplot2中显示它们:

ggplot(newData, aes(x=name, y=value)) +
    geom_col(aes(fill=gene)) +
    facet_wrap(~id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM