使用ggplot和2个过滤器叠加2个条形图

问题描述 投票:0回答:1

我有一个数据框,该数据框具有按会话和条件分组的数据。我想绘制会话vs #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的hold函数

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和Female的数字看起来并不明显。我该怎么办?

谢谢,Trishna

r ggplot2 geom-bar
1个回答
0
投票

我不确定,预期结果应该是什么,但这有帮助吗?

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)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.