【问题标题】:Can I plot values for subsets against each other in r?我可以在 r 中绘制子集的值吗?
【发布时间】:2018-10-19 00:20:18
【问题描述】:

我有一个神经认知研究的数据。我们通过三个略有不同的调查来衡量结果,这些调查具有相同的参与者可以获得的可能分数范围。我的数据是长格式的——即每个参与者都有三行,变量pointsoutcome。变量outcome 表示在给定行(scd_gbscd_rbscd_ab)中使用什么类型的调查来测量点。

    id outcome points
    1  scd_gb   20
    1  scd_rb   15
    1  scd_ab   3
    2  scd_gb   6
    2  scd_rb   18
    2  scd_ab   15

我想创建一个散点图,其中 x 轴上有 scd_gb,y 轴上有 scd_gbscd_rb,每个都有不同的颜色。

所以我有两个问题: 首先,我可以将子集相互绘制还是将数据转换为宽格式? 第二(一般而言),我可以将一个变量与其他两个变量进行对比吗?

我尝试了以下返回错误的代码。

    library(ggplot2)
    ggplot(SCD_long , aes(x = points(subset(SCD_long, outcome %in% c("scd_gb"))), 
    y = points(subset(SCD_long, outcome %in% c("scd_rb" , "scd_ab"))))) +
        geom_point(aes(color = outcome), alpha = .5)   

    Error: Aesthetics must be either length 1 or the same as the data (606): colour, x, y
In addition: Warning messages:
1: In data.matrix(x) : NAs introduced by coercion
2: In data.matrix(x) : NAs introduced by coercion
3: In data.matrix(x) : NAs introduced by coercion
4: In data.matrix(x) : NAs introduced by coercion

我认为这两个问题都可以通过数据争论来解决。我想知道是否可以在不更改数据格式的情况下收到所需的绘图。

【问题讨论】:

  • (您为轴指定了两次scd_gb。)如果您在 x 上一个(比如说)gb 而在 y 上另一个两个,则表明它们之间存在配对。我在数据中看不到这样的配对。为了对这些进行散点图,需要与 x 上发生的事情和 y 上发生的事情之间存在明确的一对一关系。照原样,没有办法做到这一点,因为您有 2 个 x 和 4 个其他。也许您的意思是每个轴都是一个 id,点的颜色是结果?

标签: r ggplot2 subset


【解决方案1】:

是的,我认为扩大数据范围将是一个好方法。这是一种方法,我已将其应用于iris 数据框子集的长格式。

like_your_data <- structure(list(points = c(5.1, 4.9, 4.7, 4.6, 7, 6.4, 6.9, 5.5, 
6.3, 5.8, 7.1, 6.3), outcome = structure(c(1L, 1L, 1L, 1L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L), .Label = c("setosa", "versicolor", 
"virginica"), class = "factor"), participant = c(1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L)), class = c("tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -12L), .Names = c("points", 
"outcome", "participant"))

首先我制作了一个只是 setosa 的版本(相当于你的scd_gb)。然后我将它加入到不包括 setosa 的版本中。这具有在一列中添加其他值的效果,在另一列中添加它们的调查类型。这适用于 ggplot,因为我们可以将调查类型映射到颜色。

like_your_data %>%
  filter(outcome == "setosa") %>% # Equiv to scd_gb
  left_join(like_your_data %>% 
              filter(outcome != "setosa"), by = "participant") %>%
  ## Output at this point:
  # A tibble: 8 x 5
  #   points.x outcome.x participant points.y outcome.y 
  # <dbl> <fct>           <int>    <dbl> <fct>     
  # 1      5.1 setosa              1      7   versicolor
  # 2      5.1 setosa              1      6.3 virginica 
  # 3      4.9 setosa              2      6.4 versicolor
  ggplot(aes(points.x, points.y, color = outcome.y)) + geom_point()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    • 2012-04-24
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多