I would like to create a function to save plots (from ggplot
).
I have many such plots so this will help me to work more effectively.
Here is a data frame:
### creating data frame
music <- c("Blues", "Hip-hop", "Jazz", "Metal", "Rock")
number <- c(8, 7, 4, 6, 11)
df.music <- data.frame(music, number)
colnames(df.music) <- c("Music", "Amount")
Then I create a plot:
### creating bar graph (this part is OK)
myplot <- ggplot(data=df.music, aes(x=music, y=number)) +
geom_bar(stat="identity") +
xlab(colnames(df.music)[1]) +
ylab(colnames(df.music)[2]) +
ylim(c(0,11)) +
ggtitle("Ulubiony typ muzyki wśród studentów")
Now I want to save this plot to .pdf
.
This works:
pdf("Myplot.pdf", width=5, height=5)
plot.music.bad
dev.off()
However I would like to automate this with a function which takes as an argument the plot I want to save. I don't know exactly how to do it; here's what I have tried:
save <- function(myplot){
plot<- myplot
pdf("lol.pdf", width=5, height=5)
plot
dev.off()
}
### .pdf file is created but doesn't work
save(myplot)
So, how can I do it?
If you would like an image file instead of a pdf, also the following works
or with additional parameters, as follows.
Also following file types are supported "eps", "ps", "tex" (pictex), "pdf", "jpeg", "tiff", "png", "bmp", "svg" or "wmf".
You can use
print()
to save plots produced fromggplot2
to a file.First, define your function to save plots:
Create your plot:
And finally call the function:
Alternatively, you could just use
ggsave()
after creating your plot:Following was useful for me, may be for someone else as well. One can save the last plot without explicitly referring it as well.