0

I try to save a ggplot in a pdf in my wd. The pdf file is created but does not contain anything. Here is what I have :

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

The loop and the ggplot are working. I don't have any error message. But still I can't open the pdf because nothing is writen in it ?

Thank you for the help!

jo.H
  • 59
  • 4

1 Answers1

0

Don't use pdf() and dev.off() with ggplot2. Use ggsave()

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

See ?ggsave for more options, such as output dimensions, units, etc.

EDIT

In response to your comment, place the ggsave() inside the for() loop, and save the plot to a different file name each time. For example:

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

This pastes the iteration number into the filename so the same file isn't overwritten each time.

Phil
  • 4,344
  • 2
  • 23
  • 33
  • Indeed it works, but it only saves the last plot. this is due to the parameters : `plot=last_plot()`. How do I change this parameter so it saves all the plot of my loop ? – jo.H May 21 '17 at 10:34
  • 1
    @jo.H See my edit for an approach you could use to solve this. – Phil May 21 '17 at 12:27
  • any chance to save them all in the same pdf file? – jo.H May 21 '17 at 18:05
  • @jo.H You'd need to look into `facet()` but you need a grouping variable in your data to do this. This is a good resource for `facet`s: http://www.cookbook-r.com/Graphs/Facets_(ggplot2)/ If you struggle I'd open a new question and post a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Phil May 22 '17 at 10:16