简体   繁体   English

ggplot2 条形图按两个变量分组,然后再由两个变量堆叠

[英]ggplot2 barchart grouped by two variables and then stacked by two more

I just can't quite get this plot working.我只是不能完全让这个 plot 工作。 I have one more variable than the examples I can find on here.我比我在这里能找到的例子多了一个变量。 I have a dataset like so:我有一个像这样的数据集:

df <- data.frame(
   Type=sample(c('A', 'B', 'C', 'D'), 30, T),
   Geno=rep(LETTERS[1:3], 10), 
   Count=sample(1:5, 30, T), 
   subcount=sample(1:2, 30, T))

And I want to make a barchart where each Type is on the X axis and Count is one the y, but then in addition to the x axis being grouped by Type, I also want it grouped by Geno.我想制作一个条形图,其中每个 Type 都在 X 轴上,Count 是 y 之一,但是除了 x 轴按 Type 分组外,我还希望它按 Geno 分组。 Then I want subcount to be stacked on top of Count.然后我希望子计数堆叠在计数之上。 So that the color of each count and subcount is specified by Geno but they are not the same color.这样每个计数和子计数的颜色由 Geno 指定,但它们不是相同的颜色。

I can get it stacked by count and subcount and grouped by Element but not also geno, or I can get it grouped by geno and Type but not stacked by subcount..... Grouped but not stacked:我可以将它按计数和子计数堆叠并按元素分组但不按 geno 分组,或者我可以按 geno 和类型分组但不按子计数堆叠.....分组但不堆叠:

ggplot(df, aes(y=Count, x=Type, fill=Geno))+
    geom_bar(stat="identity", position="dodge")

An attempt where its stacked but not grouped:堆叠但未分组的尝试:

ggplot(df, aes(fill=subcount, y=Count, x=Type))+
    geom_bar(position="stack", stat="identity")

Thanks in advance for any help.提前感谢您的帮助。

Do you want this plot?你想要这个 plot 吗?

library(ggplot2)
ggplot(df, aes(fill=interaction(subcount, Geno), y=Count, x=Type))+
  geom_bar(position="stack", stat="identity")

[1]:https://i.stack.imgur.com/NENG1.png

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

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