Skip to content

ggsave in lapply - erroneously renaming plots on save #6539

Closed as duplicate of#193
@MichelineCampbell

Description

@MichelineCampbell

Hi all,

I have found a weird problem when saving lists of plots with ggsave and lapply.

I have a large dataframe of elemental data for different samples which I typically plot in batches using lapply, with plots titled by element. I noticed that the saved versions of the Fe and Sr plots get mis-titled, even when appearing as they should in the plot viewer. I have encountered both being titled "Sr" and both being titled "Fe". The behaviour seems to resolve itself if you use something like lab(plot = paste("Sample", el)), and of the 15 elements I am plotting it only seems to be Sr and Fe that get mis-titled.

This error reproduces, I have made an example below.

I am using R version 4.4.2 and ggplot2 version 3.5.2.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)
Sr <- data.frame(x = 1:100,
           y = rnorm(100),
           sample = "Sr")

Fe <- data.frame(x = 1:100,
                 y = rnorm(100) +100,
                 sample = "Fe")

all <- rbind(Sr, Fe)

vars <- unique(all$sample)

lapply(vars, function(i){
  
  el <- i
  
plot <-  all %>% filter(sample == !!i) %>% 
    ggplot(aes(x = x, y = y)) +
    geom_line() +
    labs(title = el,
         y = "Concentration (ppm)",
         x = "Year (CE)") +
    theme_bw() +
    theme(strip.background = element_blank(),
          legend.position = "bottom") +
    guides(colour=guide_legend(nrow=2,byrow=TRUE))


  
  ggsave(width = 15, height = 10, units= "cm", filename = paste0("test2", el, ".png"))
  print(plot)
  dev.off()
  
  print(plot)
})
#> [[1]]
#> 
#> [[2]]

Expected output (copied from the plot viewer)

Image

Saved output

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions