简体   繁体   English

使用 ggplot 在 R 中创建刺激

[英]Creating stimuli in R with ggplot

I am trying to generate my own stimuli for an experiment using R. Below is the code that creates my (x,y) coordinates using the rnorm() with different a sample size of 100, different means and sd.我正在尝试使用 R 为实验生成我自己的刺激。下面是使用 rnorm() 创建我的 (x,y) 坐标的代码,样本大小为 100,不同的均值和 sd。 I also create another variable to represent the size of the circles, which are determined by the runif().我还创建了另一个变量来表示由 runif() 确定的圆圈的大小。

dt <- data.frame(x = NA,
         y = NA,
         size = NA,
         M = NA, 
         sd = NA,
         col = NA,
         iter = NA)
sa<-0


mySD<-c(5, 15)
myMeans<-c(35, 45)
colors<-c("Blues", "Reds") 

for(i in 1:10){
    for(s in mySD){
      for(m in myMeans){

        x = abs(rnorm(n=1, mean=m, sd=s))
        y = abs(rnorm(n=1, mean=m, sd=s))

        size = runif(1, 1, 25) #select a random x speed between [25,35]

        sa<-sa+1
        dt[sa,] <- NA
        dt$x[sa]<-x
        dt$y[sa]<-y
        dt$M[sa]<-m
        dt$sd[sa]<-s
        dt$size[sa]<-size
        dt$iter[sa]<-i
      }
    }
  }
}

Next, I want to use ggplot(dt, aes(x, y, size=size) to plot. I want to randomly select 4 (x,y) values to plot for one graph, then 8 for another, then 16 for another, etc. Basically, I want to plot different graphs with a different number of data points. For example, some graphs that you would see would have 4 data points that vary by size and color, others would have 32 data points that vary in size and color. I m not sure how to select a set of unique data points from the data frame that I created. Any help would be great. I'm pretty new to R.接下来,我想使用 ggplot(dt, aes(x, y, size=size) 进行绘图。我想随机选择 4 个 (x,y) 值来绘制一个图,然后 8 个为另一个,然后 16 个为另一个等。基本上,我想用不同数量的数据点绘制不同的图表。例如,您会看到一些图表有 4 个数据点,它们的大小和颜色各不相同,其他图表则有 32 个大小不同的数据点和颜色。我不知道如何从我创建的数据框中选择一组独特的数据点。任何帮助都会很棒。我对 R 很陌生。

First of all, the question's data creation code can be greatly simplified, rewritten with no loops at all.首先,问题的数据创建代码可以大大简化,完全没有循环重写。 R is a vectorized language and the following will create a data frame with the same structure. R 是一种矢量化语言,下面将创建一个具有相同结构的数据框。

Don't forget to set the RNG seed, in order to make the results reproducible.不要忘记设置 RNG 种子,以使结果可重现。

library(ggplot2)

set.seed(2020)    # make the results reproducible

sd <- rep(rep(mySD, each = 2), 10)
M <- rep(myMeans, 2*10)
x <- abs(rnorm(n = 40, mean = M, sd = sd))
y <- abs(rnorm(n = 40, mean = M, sd = sd))
size <- runif(40, 1, 25)
iter <- seq_along(x)
dt2 <- data.frame(x, y, size, M, sd, iter)
dt2$col <- c("blue", "red")

Now the plots.现在的情节。 The following function accepts a data frame X as its first argument and a number of points to draw as the second one.下面的函数接受一个数据框X作为它的第一个参数和一些要绘制的点作为第二个参数。 Then plots n points chosen at random with color col and size (a continuous variable) size .然后用颜色col和大小(连续变量) size随机选择n个点。

plot_fun <- function(X, n){
  Colors <- unique(X[["col"]])
  Colors <- setNames(Colors, Colors)
  i <- sample(nrow(X), n)
  g <- ggplot(X[i,], aes(x, y, size = size, color = col)) +
    geom_point() +
    scale_color_manual(values = Colors) +
    theme_bw()
  g
}

plot_fun(dt2, 8)

To plot several values for n , produce the plots with lapply then use grid.arrange from package gridExtra .要绘制几个值n ,与产生该地块lapply然后用grid.arrange从包gridExtra

plot_list <- lapply(c(4,8,16,32), function(n) plot_fun(dt2, n))
gridExtra::grid.arrange(grobs = plot_list)

在此处输入图片说明

Individual plots are still possible with个别地块仍然可能与

plot_list[[1]]
plot_list[[2]]

and so on.等等。


Another way is to use faceting.另一种方法是使用分面。 Write another function, plot_fun_facets assigning the number of points to a new variable in the sample data frames, n , and use that variable as a faceting variable.编写另一个函数plot_fun_facets将点数分配给示例数据框中的新变量n ,并将该变量用作分面变量。

plot_fun_facets <- function(X, n){
  Colors <- unique(X[["col"]])
  Colors <- setNames(Colors, Colors)
  X_list <- lapply(n, function(.n){
    i <- sample(nrow(X), .n)
    Y <- X[i,]
    Y$n <- .n
    Y
  })
  X <- do.call(rbind, X_list)
  g <- ggplot(X, aes(x, y, size = size, color = col)) +
    geom_point() +
    scale_color_manual(values = Colors) +
    facet_wrap(~ n) +
    theme_bw()
  g
}

plot_fun_facets(dt2, c(4,8,16,32))

在此处输入图片说明

Here are two ways - depending if you wanted each group to not contain points from any other group.这里有两种方法 - 取决于您是否希望每个组不包含来自任何其他组的点。

I'll just use a dummy data frame that just has columns x , y , and size .我将只使用一个只有xysize列的虚拟数据框。

library(tidyverse)

dt <- tibble(x = runif(100), y = runif(100), size = runif(100))

Allowing groups to share the same points允许组共享相同的点

Create a vector for the size of each group.为每个组的大小创建一个向量。

sample_sizes <- 2^(seq_len(4) + 1)
sample_sizes
#> [1]  4  8 16 32

Randomly sample the data frame and add a group column.随机采样数据框并添加一个group列。

sampled <- map_dfr(
  sample_sizes,
  ~sample_n(dt, .),
  .id = "group"
)

Plot using facets.使用分面绘图。

ggplot(sampled, aes(x, y, size = size)) +
  geom_point() +
  facet_wrap(~group)

情节1

Requiring groups to have different points要求组别有不同的分数

First, we need a way to generate four 1 s, eight 2 s etc. This can be done using log2 and some tricks.首先,我们需要一种方法来生成四个1 s、八个2 s 等等。这可以使用log2和一些技巧来完成。

groups <- floor(log2(seq_len(nrow(dt)) + 3)) - 1
groups
#>  [1] 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4
#> [36] 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5
#> [71] 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5 5

Shuffle this vector and add it as a column.打乱这个向量并将其添加为一列。

dt$group <- sample(groups)

Facet using this new column to generate the desired plots. Facet 使用这个新列来生成所需的图。

ggplot(dt, aes(x, y, size = size)) +
  geom_point() +
  facet_wrap(~group)

情节2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM