Return call from ggplot object
It's not currently possible to go from a ggplot2 object to the code that (might have) created it.
R programming: return ggplot object instead of grob?
I you want special behaviour of printing the object your function returns, you can wrap it in an S3 class and write a custom print method for it. In this case, the print method would then plot the outcome.
library(ggplot2)
my_fn <- function() {
iris_list <- split(iris, iris$Species)
plots_laidout <- list()
for (yvar in c('Sepal.Length', 'Petal.Length', 'Petal.Width')) {
plot_list <- lapply(iris_list, function(dat) ggplot2::ggplotGrob(
ggplot2::ggplot(dat, ggplot2::aes_string(x = 'Sepal.Length', y = yvar)) +
ggplot2::geom_point()
))
plot_list <- do.call(gridExtra::gtable_cbind, plot_list)
# Set new class
class(plot_list) <- c("my_class", class(plot_list))
plots_laidout[[length(plots_laidout) + 1]] <- plot_list
}
return(plots_laidout)
}
# Define an S3 print method
print.my_class <- function(x, newpage = TRUE) {
if (newpage) {
grid::grid.newpage()
}
grid::grid.draw(x)
invisible(x)
}
output <- my_fn()
# Outputs plot when printing elements of output
output[[1]]
Created on 2021-04-05 by the reprex package (v1.0.0)
Return both a base plot and ggplot from function
I've never used base plot, but in a few attemps and coming across recordPlot(), as @user2554330 (beat me for 2 minutes) says, you can save both plots. Changing the order of plot() and ggplot() worked for me so first plot() is called and not overwritte ggplot() output. Also you can store the list in a variable and call the objects then.
library(tidyverse)
library(mtcars)
library(ggplot2)
my.fun = function(){
mod.lm = lm(mpg ~ disp, data = mtcars)
par(mfrow = c(2,2))
plot(mod.lm)
p1 <- recordPlot()
p2 <- mtcars %>%
ggplot(aes(x = disp, y = disp))+
geom_point()
list(p1, p2)
}
my.fun()
a <- my.fun()
How can I catch errors that occur when ggplot objects are evaluated within a pipe?
The error happens when the plot is built by ggplot_build()
. Normally you don't call this directly, it's called by the functions that display the object, but you can call it yourself. For example,
if (inherits(try(ggplot_build(plot)), "try-error"))
plot <- ggplot()
will replace a bad plot by a blank one.
ggplot2 return values
In ggplot2 (3.3.5)
, I can not get access to the returned data frame with ggplot2:::print.ggplot()
, but I get success with ggplot_build
:
simple <- data.frame(x = rep(1:10, each = 2))
tmp <- ggplot(data=simple) + stat_bin(aes(x), binwidth=0.1)
# with ggplot_build
x <- ggplot_build(tmp)
head(x[["data"]][[1]])
# y count x xmin xmax density ncount ndensity flipped_aes PANEL group ymin ymax colour fill size linetype alpha
# 1 2 2 1.0 0.95 1.05 1 1 1 FALSE 1 -1 0 2 NA grey35 0.5 1 NA
# 2 0 0 1.1 1.05 1.15 0 0 0 FALSE 1 -1 0 0 NA grey35 0.5 1 NA
# 3 0 0 1.2 1.15 1.25 0 0 0 FALSE 1 -1 0 0 NA grey35 0.5 1 NA
# 4 0 0 1.3 1.25 1.35 0 0 0 FALSE 1 -1 0 0 NA grey35 0.5 1 NA
# 5 0 0 1.4 1.35 1.45 0 0 0 FALSE 1 -1 0 0 NA grey35 0.5 1 NA
# 6 0 0 1.5 1.45 1.55 0 0 0 FALSE 1 -1 0 0 NA grey35 0.5 1 NA
Related Topics
R Cleaning Up a Character and Converting It into a Numeric
Help Understand the Error in a Function I Defined in R
R Dplyr Subset with Missing Columns
How to Drop Factor Levels While Scraping Data Off Us Census HTML Site
R Replacing Zeros in Dataframe with Next Non Zero Value
Add a Series of Elements in Different Locations Within a Vector
Change Value to Percentage of Row in R
How to Create a Binary Vector with 1 If Elements Are Part of the Same Vector
How to Use Geom_Rect with Discrete Axis Values
Adding a New Column to Matrix Error
R - Calculate Test Mse Given a Trained Model from a Training Set and a Test Set
How to Automate Nested Sections in Rmds Which Include Text, Maps and Tables
Choose Specific Number with Probability
Using Ggplot2 with Columns That Have Spaces in Their Names
Terms of a Sum in a R Expression
Collapse/Concatenate/Aggregate Multiple Columns to a Single Comma Separated String Within Each Group