Save ggplot with a function

前端 未结 3 1704
北荒
北荒 2021-01-31 08:21

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

Here is a data frame:

### creating data frame
music <- c(\"Blues\", \"Hip-         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-31 08:23

    You can use print() to save plots produced from ggplot2 to a file.

    First, define your function to save plots:

    savePlot <- function(myPlot) {
            pdf("myPlot.pdf")
            print(myPlot)
            dev.off()
    }
    

    Create your plot:

     myPlot <- ggplot(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")
    

    And finally call the function:

    savePlot(myPlot)
    

    Alternatively, you could just use ggsave() after creating your plot:

    ggsave(filename="myPlot.pdf", plot=myPlot)
    

提交回复
热议问题