使用功能保存ggplot [英] Save ggplot with a function
本文介绍了使用功能保存ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建一个函数来保存绘图(来自ggplot
).
I would like to create a function to save plots (from 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
.
Now I want to save this plot to .pdf
.
这有效:
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)
那我该怎么办?
推荐答案
您可以使用print()
将由ggplot2
生成的图保存到文件中.
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()
}
创建剧情:
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)
这篇关于使用功能保存ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文