【问题标题】:can't write pdf in R无法在 R 中编写 pdf
【发布时间】:2017-05-21 10:00:27
【问题描述】:

我尝试将 ggplot 保存在我的 wd 中的 pdf 中。 pdf 文件已创建但不包含任何内容。这是我所拥有的:

pdf("enrich_prof_eu.pdf",height = 7,width =10)
par(mfrow=c(1,2),mar=c(4, 4.1, 5.5, 1) + 
0.1,mgp=c(2.1,0.7,0),cex.axis=1.2,pch=3)

for (i in el){
df=data.frame(horizon = c("h1", "h2", "h3", "h4"), val =yeubis[,i])
ggplot(df, aes(x=val,y=horizon)) +
geom_point() +
geom_segment(aes(x=df$val[1], y=df$horizon[1], xend=df$val[2], 
yend=df$horizon[2])) +
geom_segment(aes(x=df$val[2], y=df$horizon[2], xend=df$val[3], 
yend=df$horizon[3])) +
geom_segment(aes(x=df$val[3], y=df$horizon[3], xend=df$val[4], 
yend=df$horizon[4])) +
scale_y_discrete(limits = rev(levels(df$horizon)))+
scale_x_continuous(position = "top") +
labs(x=paste(i,"[ppm]"))
}
dev.off()

循环和 ggplot 正在工作。我没有任何错误信息。但是我仍然无法打开pdf,因为里面没有写任何东西?

感谢您的帮助!

【问题讨论】:

  • 你想在 for 循环中 print()ggplots

标签: r pdf ggplot2


【解决方案1】:

不要将pdf()dev.off()ggplot2 一起使用。使用ggsave()

ggplot(data = df, aes(x, y)) + geom_segment(...)
ggsave("enrich_prof_eu.pdf")

有关更多选项,例如输出尺寸、单位等,请参阅?ggsave

编辑

响应您的评论,将ggsave() 放在for() 循环中,并每次将绘图保存为不同的文件名。例如:

for (i in seq_along(variables)) {
  ggplot(df, aes(x, y)) + geom_segment(...)
  ggsave(paste0("enrich_prof_eu_", i, ".pdf"))
}

这会将迭代编号粘贴到文件名中,因此不会每次都覆盖同一个文件。

【讨论】:

  • 确实有效,但它只保存了最后一个情节。这是由于参数:plot=last_plot()。如何更改此参数以保存循环的所有图?
  • @jo.H 查看我的编辑,了解可以用来解决此问题的方法。
  • 有没有机会将它们全部保存在同一个 pdf 文件中?
  • @jo.H 您需要查看facet(),但您需要在数据中使用分组变量来执行此操作。这是facets 的好资源:cookbook-r.com/Graphs/Facets_(ggplot2) 如果您遇到困难,我会打开一个新问题并发布reproducible example
猜你喜欢
  • 2017-02-17
  • 1970-01-01
  • 2021-07-06
  • 2020-06-07
  • 2020-11-26
  • 1970-01-01
  • 2018-07-03
  • 2021-05-21
  • 2015-04-04
相关资源
最近更新 更多