根据标准划分数据框并使用 ggplot2 绘制结果

Dividing a dataframe based on a criterion and plotting the result using ggplot2

我还是 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 个是左侧的命中)- 它与我之前的 post 类似,但还有 1 个条件:

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

我用下面的代码完成了:

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")

剧情是这样的:

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

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

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

那么你应该能够绘制甚至绘制 "HitR" 和 "HitL" 的子图以进行比较。如果这有帮助,请告诉我。

是这样的吗?

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-06-25 创建