ggplot2:geom_bar with group,position_dodge和fill

Tin*_*ero 6 r ggplot2 geom-bar

我正在尝试生成一个条形图,使得x轴是患者,每个患者都有多个样本.因此,例如(使用mtcars数据作为数据的模板):

library("ggplot2")
ggplot(mtcars, aes(x = factor(cyl), group = factor(gear))) +
   geom_bar(position = position_dodge(width = 0.8), binwidth = 25) +
   xlab("Patient") +
   ylab("Number of Mutations per Patient Sample")
Run Code Online (Sandbox Code Playgroud)

这会产生这样的东西:

在此输入图像描述

每个条形图代表每个患者的样本.

我想通过使用颜色填充条形图来添加关于每个患者样本的其他信息(例如,每个患者样本中的不同类型的突变).我以为我可以像这样指定fill参数:

ggplot(mtcars, aes(x = factor(cyl), group = factor(gear), fill = factor(vs))) +
   geom_bar(position = position_dodge(width = 0.8), binwidth = 25) +
   xlab("Patient") +
   ylab("Number of Mutations per Patient Sample")
Run Code Online (Sandbox Code Playgroud)

但这并不会为每个患者样本条形图产生"堆积条形图".我假设这是因为position_dodge()已设置.反正有没有绕过这个?基本上,我想要的是:

ggplot(mtcars, aes(x = factor(cyl), fill = factor(vs))) +
   geom_bar() +
   xlab("Patient") +
   ylab("Number of Mutations per Patient Sample")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

但是我列出的第一个图中有这些颜色.这可能与ggplot2有关吗?

krl*_*mlr 7

我认为facets是你最接近你想要的东西:

ggplot(mtcars, aes(x = factor(gear), fill = factor(vs))) +
    geom_bar(position = position_dodge(width = 0.8), binwidth = 25) +
    xlab("Patient") +
    ylab("Number of Mutations per Patient Sample") +
    facet_wrap(~cyl)
Run Code Online (Sandbox Code Playgroud)

情节结果

我没有在ggplot2的问题跟踪器中找到任何相关内容.