This question already has an answer here:
Generate multiple graphics from within an R function
(1 answer)
Closed 3 years ago.
I need to make a bunch of individual plots and want to accomplish this in a for loop. I am using ggplot2. I would just use the facet option if it could save each graph in a separate file, which I don't think it can do.
There is something going on because the plots are not saved into the files. The files are generated, though, but are empty. Here is an idea of what my code looks like:
for(i in 1:15) {
pdf(paste("path/plot", i, ".pdf", sep=""), width=4, height=4)
abc <- ggplot(data[data[,3]==i,],
aes(variable, value, group=Name, color=Name)) +
geom_point(alpha=.6, size=3)+geom_line() +
theme(legend.position="none", axis.text.x = element_text(angle = -330)) +
geom_text(aes(label=Name),hjust=0, vjust=0, size=2.5) +
ggtitle("Title")
abc
dev.off()
}
How can I save the plots into these files?
Note that if I has a numeric value and I run the code inside the for loop, everything works.
When I use print it works:
for(i in 1:15) {
pdf(paste("plot", i, ".pdf", sep=""), width=4, height=4)
abc <- ggplot(mtcars, aes(cyl, disp)) +
geom_point(alpha=.6, size=3)
print(abc)
dev.off()
}
Or try ggsave:
for(i in 1:15) {
Filename <- paste("plot", i, ".pdf", sep="")
abc <- ggplot(mtcars, aes(cyl, disp)) +
geom_point(alpha=.6, size=3)
ggsave(filename = Filename, abc, width=4, height=4)
}
Related
This question already has an answer here:
Generate multiple graphics from within an R function
(1 answer)
Closed 3 years ago.
I need to make a bunch of individual plots and want to accomplish this in a for loop. I am using ggplot2. I would just use the facet option if it could save each graph in a separate file, which I don't think it can do.
There is something going on because the plots are not saved into the files. The files are generated, though, but are empty. Here is an idea of what my code looks like:
for(i in 1:15) {
pdf(paste("path/plot", i, ".pdf", sep=""), width=4, height=4)
abc <- ggplot(data[data[,3]==i,],
aes(variable, value, group=Name, color=Name)) +
geom_point(alpha=.6, size=3)+geom_line() +
theme(legend.position="none", axis.text.x = element_text(angle = -330)) +
geom_text(aes(label=Name),hjust=0, vjust=0, size=2.5) +
ggtitle("Title")
abc
dev.off()
}
How can I save the plots into these files?
Note that if I has a numeric value and I run the code inside the for loop, everything works.
When I use print it works:
for(i in 1:15) {
pdf(paste("plot", i, ".pdf", sep=""), width=4, height=4)
abc <- ggplot(mtcars, aes(cyl, disp)) +
geom_point(alpha=.6, size=3)
print(abc)
dev.off()
}
Or try ggsave:
for(i in 1:15) {
Filename <- paste("plot", i, ".pdf", sep="")
abc <- ggplot(mtcars, aes(cyl, disp)) +
geom_point(alpha=.6, size=3)
ggsave(filename = Filename, abc, width=4, height=4)
}
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!
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.
I'm pretty happy with the results I'm getting with R. Most of my stacked histogram plots are looking fine, e.g.
and
However, I have a few that have so many categories in the legend that the legend is crowing out the plot, e.g.
How can I fix this?
Here is my plot.r, which I call on the command line like this
RScript plot.r foo.dat foo.png 1600 800
foo.dat
account,operation,call_count,day
cal3510,foo-method,1,2016-10-01
cra4617,foo-method,1,2016-10-03
cus4404,foo-method,1,2016-10-03
hin4510,foo-method,1,2016-10-03
mas4484,foo-method,1,2016-10-04
...
entirety of foo.dat: http://pastebin.com/xnJtJSrU
plot.r
library(ggplot2)
library(scales)
args<-commandArgs(TRUE)
filename<-args[1]
png_filename<-args[2]
wide<-as.numeric(args[3])
high<-as.numeric(args[4])
print(wide)
print(high)
print(filename)
print(png_filename)
dat = read.csv(filename)
dat$account = as.character(dat$account)
dat$operation = as.character(dat$operation)
dat$call_count = as.integer(dat$call_count)
dat$day = as.Date(dat$day)
png(png_filename,width=wide,height=high)
p <- ggplot(dat, aes(x=day, y=call_count, fill=account))
p <- p + geom_histogram(stat="identity")
p <- p + scale_x_date(labels=date_format("%b-%Y"), limits=as.Date(c('2016-10-01','2017-01-01')))
print(p)
dev.off()
Answer from #PierreLafortune
using:
p <- p + theme(legend.position="bottom")
p <- p + guides(fill=guide_legend(nrow=5, byrow=TRUE))
I'm generating pdf reports using ggplot2. Code looks something like this
pdf()
for (){
p <- ggplot(..)
print(p)
}
dev.off()
Sometimes because of the data quality ggplot fails to generate the plot. There could be multiple reasons, and we don't want to check all possible combinations for data failing. We simply want to check if ggplot fails - and continue. This is what I came up with - this works, but there are some issues.
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
geom_point()
p.bad <- ggplot(mtcars, aes(wt, as.character(mpg))) +
geom_point() +
scale_y_continuous()
pdf()
a <- try(print(p), silent = TRUE) # double printing
if (class(a)!='try-error'){
print(p)
}
b <- try(print(p.bad), silent = TRUE)
if (class(b)!='try-error'){
print(p.bad)
}
dev.off()
try(print) - generates a chart if there is no error. Is there a way of preventing it? This will probably the best solution. If we do the following - there is no double printing, but second try(print) generates blank page.
pdf()
a <- try(print(p), silent = TRUE)
b <- try(print(p.bad), silent = TRUE)
dev.off()
Is there another way of finding out if ggplot will generate an error?
I suggest to use ggsave:
ttt <- function() {
require(ggplot2)
p.bad <- ggplot(mtcars, aes(wt, as.character(mpg))) +
geom_point() +
scale_y_continuous()
a <- try(ggsave("test.pdf",p.bad))
return("test")
}
ttt()
# Saving 12.9 x 9.58 in image
# Error : Discrete value supplied to continuous scale
# [1] "test"
I use
frame <- read.table(paste('data', fname, sep="/"), sep=",", header=TRUE)
colnames(frame) <- c("pos", "word.length")
plot <- ggplot(frame, aes(x=pos, y=word.length)) + xlim(0,20) + ylim(0,20) + geom_density2d() + stat_density2d(aes(color=..level..))
png(paste("graphs/", fname, ".png", sep=""), width=600, height=600)
print(plot)
dev.off()
to create plots, but they get cut off. How do I fix this?
http://ompldr.org/vZTN0eQ
The data I used to create this plot: http://sprunge.us/gKiL
According to the ggplot2 book, you use scale_x_continuous(limits=c(1,20)) instead of xlim(1,20) for that.