Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create ggplot2 plot in memory?

Tags:

r

ggplot2

I'm trying to capture the result of a ggplot2 graphic creation in memory, to send it to a server. Has anyone a good idea how to solve that?

My code looks currently like this:

data(mtcars)
x <- ggplot(mtcars, aes(x=mpg, y=hp)) +
  geom_point(shape=1)
print(x) # RStudio can capture the output, but I'm unable to do it.
ggsave(filename="a.jpg", plot=x) # not really a solution, need it not on disk, but as blob in memory.
like image 940
Christian Sauer Avatar asked Oct 02 '15 11:10

Christian Sauer


People also ask

What does Geom_point () do in R?

The function geom_point() adds a layer of points to your plot, which creates a scatterplot. ggplot2 comes with many geom functions that each add a different type of layer to a plot.

Does ggplot work with Dataframe?

The dataframe is the first parameter in a ggplot call and, if you like, you can use the parameter definition with that call (e.g., data = dataframe ). Aesthetics are defined within an aes function call that typically is used within the ggplot call.

What is the difference between plot and ggplot in R?

Base R plots two vectors as x and y axes and allows modifications to that representation of data whereas ggplot2 derives graphics directly from the dataset. This allows faster fine-tuning of visualizations of data rather than representations of data stitched together in the Base R package1.

What is GG in ggplot?

ggplot2 is a system for declaratively creating graphics, based on The Grammar of Graphics. You provide the data, tell ggplot2 how to map variables to aesthetics, what graphical primitives to use, and it takes care of the details.


1 Answers

You can do this with the magick package.

library(magick)
data(mtcars)
x <- ggplot(mtcars, aes(x=mpg, y=hp)) +
  geom_point(shape=1)
fig <- image_graph(width = 400, height=400, res=96)
print(x)
dev.off()
figpng <- image_write(fig, path=NULL, format="png")

figpng is now a raw vector of a png of your plot.

like image 130
Bob Avatar answered Oct 17 '22 17:10

Bob