Skip to content

patchwork plots cause internal data to be dumped into chunk outputs #13470

Closed

Description

@kevinushey

System details

RStudio Edition : 2023.08.0-daily+60
RStudio Version : Desktop [Open Source]
OS Version      : macOS Ventura 13.5
R Version       : R version 4.3.1 (2023-06-16)

Steps to reproduce the problem

From thomasp85/patchwork#231.

library(ggplot2)
library(patchwork)
gg1 <- ggplot(mtcars, aes(mpg, cyl)) + 
  geom_point()

gg2 <- ggplot(mtcars, aes(hp, disp)) + 
  geom_point()

foo <- gg1 + gg2 + plot_layout(ncol = 1)

Describe the problem in detail

A data.frame is printed, which is not expected.

Screenshot 2023-08-08 at 9 37 50 AM

Describe the behavior you expected

There shouldn't be any chunk outputs after executing this code.

Session Info
Tracing print(rInfo) on entry 
[1] "hi"
R version 4.3.1 (2023-06-16)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Ventura 13.5

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib 
LAPACK: /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/lib/libRlapack.dylib;  LAPACK version 3.11.0

locale:
Tracing print(strsplit(x$locale, ";", fixed = TRUE)[[1]], quote = FALSE,  .... on entry 
[1] "hi"
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

time zone: America/Los_Angeles
tzcode source: internal

attached base packages:
Tracing print(x$basePkgs, quote = FALSE, ...) on entry 
[1] "hi"
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
Tracing print(mkLabel(x, "otherPkgs"), quote = FALSE, ...) on entry 
[1] "hi"
[1] patchwork_1.1.2 ggplot2_3.4.2  

loaded via a namespace (and not attached):
Tracing print(mkLabel(x, "loadedOnly"), quote = FALSE, ...) on entry 
[1] "hi"
 [1] vctrs_0.6.3       cli_3.6.1         knitr_1.43        rlang_1.1.1.9000 
 [5] xfun_0.39         DBI_1.1.3         generics_0.1.3    textshaping_0.3.6
 [9] labeling_0.4.2    glue_1.6.2        colorspace_2.1-0  htmltools_0.5.5  
[13] ragg_1.2.5        scales_1.2.1      fansi_1.0.4       rmarkdown_2.23   
[17] grid_4.3.1        evaluate_0.21     munsell_0.5.0     tibble_3.2.1     
[21] fastmap_1.1.1     yaml_2.3.7        lifecycle_1.0.3   compiler_4.3.1   
[25] dplyr_1.1.2       pkgconfig_2.0.3   rstudioapi_0.15.0 farver_2.1.1     
[29] systemfonts_1.0.4 digest_0.6.33     R6_2.5.1          tidyselect_1.2.0 
[33] utf8_1.2.3        pillar_1.9.0      magrittr_2.0.3    withr_2.5.0      
[37] tools_4.3.1       gtable_0.3.3     

Activity

  1. kevinushey commented on Aug 8, 2023

    @kevinushey
    CollaboratorAuthor

    I've taken a look, and it looks like a bug in RStudio. To explain the behavior:

    1. When executing a Notebook chunk, RStudio inserts its own print() overrides, so that it can detect and capture attempts to print R objects. This is what allows RStudio to capture e.g. data.frame print-outs in a clean way.
    2. RStudio also tries to detect changes to objects in the Environment pane as code chunks are executed. When new objects are created, or changed, we try to introspect those new objects to learn a bit more about those objects.
    3. To that end, when inspecting the foo object, we call str(foo) -- but this involves calling print() when examining some of the internal data in foo.
    4. Unfortunately, because the print() overrides in (1) are still active, we end up inadvertently capturing that output into the Notebook chunk.

    I think we can fix this on the RStudio side by making sure we deactivate our print overrides when updating the Environment pane.

  2. kevinushey commented on Aug 8, 2023

    @kevinushey
    CollaboratorAuthor

    .rs.addFunction("dataCaptureOverrides", function(outputFolder, libraryFolder)
    {
    defaultOverride <- function(x, options) list(x = x, options = options, className = class(x), nRow = .rs.scalar(nrow(x)), nCol = .rs.scalar(ncol(x)))
    c(
    "print.data.frame" = defaultOverride,
    "print.tbl_df" = defaultOverride,
    "print.paged_df" = defaultOverride,
    "print.grouped_df" = defaultOverride,
    "print.rowwise_df" = defaultOverride,
    "print.tbl_sql" = defaultOverride,
    "print.data.table" = function(x, options) {
    shouldPrintTable <- TRUE
    if ("data.table" %in% loadedNamespaces() &&
    exists("shouldPrint", envir = asNamespace("data.table")))
    {
    shouldPrint <- get("shouldPrint", envir = asNamespace("data.table"))
    shouldPrintTable <- tryCatch(
    shouldPrint(x) || !inherits(x, "data.table"),
    error = function(e) TRUE
    )
    }
    if (!shouldPrintTable) {
    return(NULL)
    }
    list(x = x, options = options, className = class(x), nRow = .rs.scalar(nrow(x)), nCol = .rs.scalar(ncol(x)))
    },
    "print.tbl_lazy" = function(x, options) {
    tblLazyData <- lapply(dplyr::tbl_vars(x), function(e) character(0))
    names(tblLazyData) <- dplyr::tbl_vars(x)
    lazyFrame <- do.call("data.frame", tblLazyData)
    list(
    x = lazyFrame,
    options = options,
    className = class(x),
    nRow = "?",
    nCol = "?"
    )
    }
    )
    })

  3. added this to the Backlog-2 milestone on Aug 14, 2023
  4. modified the milestones: Backlog-2, Later on Oct 5, 2023
  5. bshor commented on May 29, 2025

    @bshor

    I still see this error in patchwork. But it goes away if I simply do

    plot1 + plot2

    Instead of assigning that to an object and printing the object.

  6. AlbertoFabbri93 commented on Aug 7, 2025

    @AlbertoFabbri93

    I am experiencing the same problem with the DimPlot() function from the Seurat package:

    # View UMAP with macrophages and patient clusters
    macrophage_cells_patient_id_plot <- DimPlot(
      breast_cancer_patients_macrophage_cells,
      reduction = "umap",
      group.by = "Patient.ID",
    )
    macrophage_cells_patient_id_plot

    If I do not assign the plot to a variable the data.frame is not printed.

  7. removed this from the Later milestone on Aug 7, 2025
  8. ronblum commented on Aug 11, 2025

    @ronblum
    Contributor

    Note: This is only an issue when running chunks--not an issue when knitting the file.

  9. added this to the Apple Blossom milestone on Aug 11, 2025
  10. self-assigned this
    on Aug 21, 2025
  11. ronblum commented on Sep 17, 2025

    @ronblum
    Contributor

    Verified in RStudio Desktop 2025.11.0-daily+146 on Windows 11. Also made sure that if the objects are added to the end of the chunk, they show up in the output.

    1. Checked in R Markdown and Quarto documents.
    2. Checked with both the original ggplot2 example and the subsequent Seurat case. I wasn't familiar with DimPlot so I used the following, generated with the help of a robot:
    ```{r}
    # Minimal example of DimPlot with generated data
      library(Seurat)
      set.seed(42)
    
      # Create a minimal synthetic dataset
      gene_count <- 100
      cell_count <- 50
      data <- matrix(rpois(gene_count * cell_count, lambda = 5), nrow = gene_count)
      rownames(data) <- paste0("Gene", 1:gene_count)
      colnames(data) <- paste0("Cell", 1:cell_count)
    
      # Create Seurat object
      seurat_obj <- CreateSeuratObject(counts = data)
    
      # Add metadata with two groups for visualization
      seurat_obj$group <- sample(c("GroupA", "GroupB"), ncol(seurat_obj), replace = TRUE)
    
      # Basic preprocessing
      seurat_obj <- NormalizeData(seurat_obj)
      seurat_obj <- FindVariableFeatures(seurat_obj, nfeatures = 50)
      seurat_obj <- ScaleData(seurat_obj)
      seurat_obj <- RunPCA(seurat_obj, npcs = 10)
      seurat_obj <- FindNeighbors(seurat_obj, dims = 1:5)
      seurat_obj <- FindClusters(seurat_obj, resolution = 0.5)
      seurat_obj <- RunUMAP(seurat_obj, dims = 1:5)
    
      # Plot using DimPlot
    x <- DimPlot(seurat_obj, group.by = "group", pt.size = 1.5)
    ```
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions