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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With