Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205301

Save ggplot with a function

$
0
0

I would like to create a function to save plots (from ggplot).

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?


Viewing all articles
Browse latest Browse all 205301

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>