首页 > 解决方案 > 用 ggplot 和 2 个过滤器叠加 2 个条形图

问题描述

我有一个数据框,其中包含按会话和条件分组的数据。我想绘制会话与#hits,按条件着色并按性别过滤。

这是我的数据样本:

library(tidyverse)

    df <- tribble(
        ~session, ~condition, ~sex, ~Obs_target_hits_mean 
        , 0          , 1       , "F"    , 3
        , 1          , 2       , "F"    , 3
        , 2          , 1       , "F"    , 1
        , 3          , 1       , "F"    , 2
        , 0          , 3       , "M"    , 4
        , 1          , 2       , "M"    , 1
        , 2          , 2       , "M"    , 1
        , 3          , 3       , "M"    , 1
        , 0          , 1       , "M"    , 2
        , 1          , 1       , "M"    , 3
    )

这是我的代码,但这个数字看起来很奇怪。理想情况下,我想要类似于 MATLAB 的保持功能的图

df1 <- df %>% filter(sex=="F")
df2 <- df %>% filter(sex=="M")
ggplot() + 
geom_bar(stat = "identity", data = df1, aes(x = df1$session, y = 
         df1$obs_target_hits_mean), fill = df1$condition) +
geom_bar(stat = "identity", data = df2, aes(x = df2$session, y = 
         df2$obs_target_hits_mean), color= df2$condition, alpha = 0.5)

M 和女性的数字看起来并不明显。我应该怎么办?

谢谢,特里希娜

标签: rggplot2geom-bar

解决方案


我不完全知道,预期的结果应该是什么,但这有帮助吗?

library(tidyverse)

df <- tribble(
    ~session, ~condition, ~sex, ~hits
    , 0          , 1       , "F"    , 3
    , 1          , 2       , "F"    , 3
    , 2          , 1       , "F"    , 1
    , 3          , 1       , "F"    , 2
    , 0          , 3       , "M"    , 4
    , 1          , 2       , "M"    , 1
    , 2          , 2       , "M"    , 1
    , 3          , 3       , "M"    , 1
    , 0          , 1       , "M"    , 2
    , 1          , 1       , "M"    , 3
)

df %>%
    group_by(session, condition, sex) %>%
    summarise(obs_target_hits_mean = mean(hits)) %>%
    ggplot(aes(session, obs_target_hits_mean, fill = factor(condition))) +
    geom_bar(stat = "identity", position = "dodge") +
    facet_grid(. ~ sex)

在此处输入图像描述


推荐阅读