【问题标题】:Dividing a dataframe based on a criterion and plotting the result using ggplot2根据标准划分数据框并使用 ggplot2 绘制结果
【发布时间】:2023-03-05 02:25:01
【问题描述】:

我还是 R 新手,在绘制类似于此的数据时遇到问题:

set.seed(529)
test <- data.frame(StartPos = rep(1:10, times = 10),
                   Response = c(sample(c("H", "M", "W"), 50, replace=T),
                              sample(c("M", "W"), 50, replace = T)),
                   Velocity = c(sample(c(-36, 36), 100, replace = T)))
head(test)

基于标准。

数据由 100 行组成,起始位置为 3-5 和 10-11(每个随机生成 10 次(大约 20 次,如起始位置 3,可能存在 20 次))。每个起始位置也有一个答案,可以是 H 表示命中、M 表示未命中或 W 表示错误。某个起始位置可能没有 H。还有一个名为 Velocity 的列,其值 -36 和 36 描述了从某个 StartPos 开始的 Stimlus 的方向(右侧 -36,左侧 36)。

我想为条形图中的每个起始位置绘制每侧的命中数(HitR 和 HitL)(例如,StartPos 3 的 20 个命中中有 17 个命中,其中 7 个是右侧的命中 - 其他 10 个是左边的命中) - 这与我之前的帖子类似,还有 1 个条件:ggplot2 alternatives to fill in barplots, occurence of factor in multiple rows

我能够计算出点击次数。但没有判断是右击还是左击的标准。

我通过以下代码实现了这一点:

hit_counts <- test %>%
  mutate(StartPos = as.factor(StartPos)) %>% 
  filter(Response == "H") %>% 
  count(StartPos, .drop = FALSE) 

hit_counts

ggplot(hit_counts, aes(x = StartPos,y=n)) +
  geom_col()+labs(x="StartPos",y="Hitrate")

剧情是这样的:

它接近我需要的,但我想不出一种方法来根据它的行进方向划分或总结 Hits,然后绘制它们。

【问题讨论】:

  • 这会有帮助吗?这是链接(stackoverflow.com/questions/8293547/…
  • 遗憾的是,我没有找到如何使用 ggplot2 实现这一点的方法。但我会把它放在脑后,谢谢!

标签: r dataframe ggplot2 bar-chart criteria


【解决方案1】:

这样的?

set.seed(529)
test <- data.frame(StartPos = rep(1:10, times = 10),
                   Response = c(sample(c("H", "M", "W"), 50, replace=T),
                             sample(c("M", "W"), 50, replace = T)),
                   Velocity = c(sample(c(-36, 36), 100, replace = T)))
head(test)

library(dplyr)
library(ggplot2)

test <- test %>% 
    mutate(Direction = case_when( # add direction 
        Velocity < 0 ~ "Right",
        Velocity > 0 ~ "Left",
        TRUE ~ "None")) %>% 
    filter(Response=="H") %>% 
    group_by(StartPos, Direction) %>% # for each combination 
    mutate(Count=n()) # count

ggplot() +
    geom_col(data=test, mapping=aes(x=StartPos, fill=Direction, y=Count)) +
    labs(x="StartPos", y="Hitrate")

reprex package (v0.3.0) 于 2019 年 6 月 25 日创建

【讨论】:

  • 对不起,我忘记了“H”的过滤器,您的过滤器是正确的。
  • 非常感谢,这正是我想要的!我为“H”添加了过滤器,一切正常。
【解决方案2】:

这是另一个例子,我过去也做过。

`mydata2= subset (mydata, col_name == "HitR", select = c("col1", "col2", "col4"))`

然后您应该能够绘制甚至绘制“HitR”和“HitL”的子图以进行比较。让我知道这是否有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 2021-12-18
    • 2011-08-26
    • 2012-08-27
    相关资源
    最近更新 更多