【问题标题】:Save ggplot with a function用函数保存 ggplot
【发布时间】:2014-05-09 16:19:27
【问题描述】:

我想创建一个函数来保存绘图(来自ggplot)。

这是一个数据框:

### 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")

然后我创建一个情节:

### 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")

现在我想将此图保存到.pdf

这行得通:

pdf("Myplot.pdf", width=5, height=5)
plot.music.bad
dev.off()

但是,我想使用一个函数来自动执行此操作,该函数将我要保存的绘图作为参数。 我不知道该怎么做。这是我尝试过的:

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) 

那么,我该怎么做呢?

【问题讨论】:

  • 你试过ggsave 吗?

标签: r ggplot2


【解决方案1】:

您可以使用print()ggplot2 生成的绘图保存到文件中。

首先,定义保存绘图的函数:

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

创建你的情节:

 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")

最后调用函数:

savePlot(myPlot)

或者,您可以在创建情节后使用ggsave()

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

【讨论】:

    【解决方案2】:

    关注对我有用,可能对其他人也有用。也可以在不明确引用的情况下保存最后一个情节。

    ggsave("filename.pdf",  # jpg, png, eps, tex, etc.
           plot = last_plot(), # or an explicit ggplot object name,
           width = 7, height = 5, 
           units = "in", # other options c("in", "cm", "mm"), 
           dpi = 300)
    

    【讨论】:

      【解决方案3】:

      如果您想要图像文件而不是 pdf,也可以使用以下方法

      ggsave(filename="myPlot.jpg", plot=last_plot())
      

      或带附加参数,如下。

      ggsave(filename="myPlot.jpg", plot=lastplot(),
             width = 10, height = 5, 
             units = "cm", # other options are "in", "cm", "mm" 
             dpi = 200
             )
      

      还支持以下文件类型“eps”、“ps”、“tex”(pictex)、“pdf”、“jpeg”、“tiff”、“png”、“bmp”、“svg”或“wmf” ”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-02
        • 1970-01-01
        • 2020-05-27
        相关资源
        最近更新 更多