三行代码  ›  专栏  ›  技术社区  ›  Gopala

R中有Bug,还是我将ggplot保存到列表时出错了?

  •  0
  • Gopala  · 技术社区  · 5 天前

    这是我的密码:

    library(ggplot2)
    
    mtcars <- mtcars[, c('cyl', 'am', 'gear', 'mpg')]
    
    plots <- list()
    for (i in 1:3) {
        plots[[i]] <- ggplot(
          mtcars,
          aes(x = factor(mtcars[, i]), y = mtcars[, 'mpg'])
          ) + geom_point()
    }
    plots
    

    plots <- list()
    for (i in 1:3) {
        plots[[i]] <- sample(mtcars$mpg, 1)
    }
    plots
    

    使用将ggplot对象保存到列表 lapply 也可以正常工作,如下所示:

    library(ggplot2)
    
    mtcars <- mtcars[, c('cyl', 'am', 'gear', 'mpg')]
    
    lapply(
      1:3, function(i)
        ggplot(
          mtcars,
          aes(x = factor(mtcars[, i]), y = mtcars[, 'mpg'])
          ) + geom_point()
      )
    

    顺便说一句-此信息可能与以下内容相关:

    > packageVersion('ggplot2')
    [1] ‘3.3.3’
    
    
    > version
                   _                           
    platform       x86_64-apple-darwin17.0     
    arch           x86_64                      
    os             darwin17.0                  
    system         x86_64, darwin17.0          
    status                                     
    major          4                           
    minor          0.3                         
    year           2020                        
    month          10                          
    day            10                          
    svn rev        79318                       
    language       R                           
    version.string R version 4.0.3 (2020-10-10)
    nickname       Bunny-Wunnies Freak Out
    
    1 回复  |  直到 5 天前
        1
  •  2
  •   Cettt    5 天前

    问题是列表中包含 ggplot i 变量更准确地说,在运行代码之后 设置为 3 factor(mtcars[, 3]) .

    print(plots[[1]]) # prints the third plot
    i <- 1
    print(plots([[1]]) # prints the first plot because now i = 1
    

    plot_cars <- mtcars %>%
      gather(type, val, -mpg) %>%
      nest(data = c(val, mpg)) %>%
      mutate(plot = map(data, ~ggplot(.x,
        aes(x = val, y = mpg)) + geom_point()))
    
    
    plot_cars$plot[[1]]