I am trying to save a plot with ggsave()
. I enter the following:
library(ggplot2)
Test = data.frame("X" = seq(1, 10, 1), "Y" = 2*seq(1, 10, 1))
P = ggplot(
Test, aes(x=X, y=Y))+
geom_line()
ggsave(P, "test.pdf", device = "pdf")
But get the error:
Saving 7 x 7 in image
Error in UseMethod("grid.draw") :
no applicable method for 'grid.draw' applied to an object of class "character"
In most cases ggsave() is the simplest way to save your plot, but sometimes you may wish to save the plot by writing directly to a graphics device. To do this, you can open a regular R graphics device such as png() or pdf() , print the plot, and then close the device using dev. off() .
The ggsave() is a method in the ggplot2 package which is used for saving the last plot that was displayed in the screen.
2.1. The default size of the saved image is equal to the size of Plots pane (the “graphics device”) in RStudio, which can be found with dev. size() . Notice that the result of dev. size() and the message we receive when saving the plot with ggsave() give the same dimensions.
ggsave. ggsave works by default on the most recent graph that you've plotted. The only arugment it needs is a file name to save it as. By default, it will save to the directory that you're working out of.
Many R functions that save data, such as write.table()
, saveRDS()
etc. take as their first argument the object to be saved. But, this is not true for ggsave()
. Instead, by default, its first argument is the name of the file to save to. Thus, the syntax above would need to be modified in one of two ways:
ggsave(plot = P, filename = "test.pdf", device = "pdf")
ggsave("test.pdf", P, device = "pdf")
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