Cycling through R list of Seurat objects [duplicate] - r

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

can't write pdf in R

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.

Number of Observations in ggplot R

I output each of boxplot of my response variable with respect to my categorical feautures but I cannot highlight number of observations of each category. I tried stat_summary and geom_text() options which are stated here but they are not working.
How can I show them in my boxplots?
Below is my code:
for(i in 3:ncol(Train_factor)){
b<-paste("Boxplot for",colnames(Train_factor[i]))
p10 <- (ggplot(data=Train_factor, aes_string(x = names(Train_factor)[i],
y = "Response",fill=variable)) +
geom_boxplot())
plot_list[[i]] = p10
}
for (i in 3:ncol(Train_factor)) {
file_name = paste("boxplot", i, ".tiff", sep="")
tiff(file_name)
print(plot_list[[i]])
dev.off()
}
You haven't provided a reproducible example, so here's a generic example using the built-in mtcars data frame. We use geom_text() but instead of stat="identity" (the default) we use stat="count" and label=..count.. (which is the internally calculated count of the number of values) so that the displayed value will be the count of values.
library(ggplot2)
ggplot(mtcars, (aes(x=factor(cyl), y=mpg))) +
geom_boxplot() +
geom_text(aes(label=..count..), y=0, stat='count', colour="red", size=4) +
coord_cartesian(ylim=c(0,max(mtcars$mpg))) +
theme_classic()

Plots not working in for loop [duplicate]

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

How to capture ggplot2 errors?

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"

cut off density plot in ggplot2

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.

Resources