can't write pdf in R - 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.

Related

Cycling through R list of Seurat objects [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 ggsave() a grid.arranged plot as SVG

I have code that produces two separate ggplots and combines them into a single figure using gridExtra::grid.arrange.
I can save this combined figure as a PNG using ggsave(), but if I try to save it as an SVG file, I get only the second figure. How can I get both figures in one SVG file?
Edit:
This question goes beyond that addressed in How to save a plot made with ggplot2 as SVG. ggsave() for SVG works well for single images, but DOES NOT WORK with SVG for images composed with grid.arrange.
Here is the figure I'm trying to create. Code for this example is below.
library(ggplot2)
library(gridExtra)
data(EastIndiesTrade,package="GDAdata")
c1 <- ggplot(EastIndiesTrade, aes(x=Year, y=Exports)) +
ylim(0,2000) +
geom_line(colour="black", size=2) +
geom_line(aes(x=Year, y=Imports), colour="red", size=2) +
geom_ribbon(aes(ymin=Exports, ymax=Imports), fill="pink",alpha=0.5) +
ylab("Exports and Imports (millions of pounds)") +
annotate("text", x = 1710, y = 0, label = "Exports", size=5) +
annotate("text", x = 1770, y = 1620, label = "Imports", color="red", size=5) +
annotate("text", x = 1732, y = 1950, label = "Balance of Trade to the East Indies", color="black", size=6) +
theme_bw()
c2 <- ggplot(EastIndiesTrade, aes(x=Year,
y=Imports-Exports)) + geom_line(colour="blue", size=2) +
ylab("Balance = Imports - Exports (millions of pounds)") +
geom_ribbon(aes(ymin=Imports-Exports, ymax=0), fill="pink",alpha=0.5) +
annotate("text", x = 1711, y = 30, label = "Our Deficit", color="black", size=6) +
theme_bw()
grid.arrange(c1, c2, nrow=1)
Now, I try to save them with ggsave():
ggsave("east-indies-ggplot2.png", width=10, height=4) # OK
ggsave("east-indies-ggplot2.svg", width=10, height=4) # not OK -- only get the right panel
you probably can try to use patchwork package
https://patchwork.data-imaginist.com
instead of grid.arrange
Then you need to just use
c3=c1+c2
ggsave("~/Desktop/plotdm.svg")
This worked for me
Best
You can do this if you put the grid.arrange call into the ggsave function as follows:
ggsave("east-indies-ggplot2.svg", plot = grid.arrange(c1, c2, nrow=1), width=10, height=4)
It will call grid.arrange and simultaneously save the svg.

Exporting plots to PDF from R

I have scoured this site and others for an answer and can't seem to get the PDF portion of the code to work and help is greatly appreciated.
This code works fine, it loops through and creates plots for each industry in the RStudio Output:
gg <- list()
#make the plots, facet by client on each page - works well
for (p in 1:length(df)){
gg[[p]] <- ggplot(data = df[[p]], aes(x = MonthsActive, y = Participation, color = CommClient)) +
ylim(0,1) + geom_line(size = 0.8) +
scale_x_continuous(limits = c(1,13)) +
facet_wrap(~ClientName, scales="fixed") +
scale_color_hue(l = 45) +
ggtitle(sprintf("Participation Rate for %s for First Year",params[p]))
plot(gg[[p]])
}
Now when I wrap the PDF function around this I can't get it to output the plots. I have tested the destination path (Windows System) and when printed it looks okay. At one point, I got blank unreadable PDFs so the path seems to work. This code does not create individual PDFs:
gg <- list()
#make the plots, facet by client on each page
for (p in 1:length(df)){
#set the file path by name - when using print looks fine
myPath <- file.path("Q:","DataScience", "ParticipationPlots", paste(params[p], ".pdf", sep=""))
#set pdf as device and make individual PDFs
pdf(file = myPath, onefile = F, paper = "USr", width = 11, height = 8.5)
#this code is the same as above that works except for dev.off() at end
gg[[p]] <- ggplot(data = df[[p]], aes(x = MonthsActive, y = Participation, color = CommClient)) +
ylim(0,1) + geom_line(size = 0.8) +
scale_x_continuous(limits = c(1,13)) +
facet_wrap(~ClientName, scales="fixed") +
scale_color_hue(l = 45) +
ggtitle(sprintf("Participation Rate for %s for First Year",params[p]))
plot(gg[[p]])
}
dev.off()
dev.off() needs to be inside the loop

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

comfortable way to use unicode characters in a ggplot graph

Is there a good practice to insert unicode characters in a ggplot title and also save it as pdf?
I am struggling with expression, paste and sprintf to get a nice title...
So, what works is
ggtitle(expression(paste('5', mu, 'g')))
This will print an ugly greek mu. By ugly I mean a different font, but overall, it will be printed as pdf without problems. But the problems start, if you want to have new lines in the title. Or maybe I didn't found a solution for this.
My preferred solution would be to use sprintf with the unicode number, so for example
ggtitle(sprintf('5\u03BCg'))
It shows a nice result on the screen but it is not possible to save as pdf with ggsave. PNG works fine, but I would like to use the pdf save option.
Is there a possibility to plot the unicode characters with ggsave? I read about the cairo_pdf device, but this messes up the fonts and I can not save the plot properly.
Thanks in advance for any help.
EDIT:
Example PDF
I just uploaded an example PDF... So maybe my problem is somewhere else...
Try
library(ggplot2)
p <- ggplot(df, aes(x=date, y=value))
p <- p + geom_line()
p + ggtitle(sprintf('5\u03BCg'))
library(Cairo)
ggsave("newfile.pdf", device=cairo_pdf)
data
set.seed(42)
df <- data.frame(date = 1:10 , value = cumsum(runif(10 , max = 10)) )
Using the emojifont package fixes this issue for me.
library(emojifont)
I am sharing the tricks to have Unicode characters properly displayed on PDF files. I am currently running R-4.0.5 for Windows.
library(ggplot2)
library(gridExtra)
library(grid)
library(png)
#--- The trick to get unicode characters being printed on pdf files:
#--- 1. Create a temporary file, say "temp.png"
#--- 2. Create the pdf file using pdf() or cairo_pdf(), say "UnicodeToPDF.pdf"
#--- 3. Combine the use of grid.arrange (from gridExtra), rasterGrob (from grid), and readPNG (from png) to insert the
# temp.png file into the UnicodeToPDF.pdf file
test.plot = ggplot() +
geom_point(data = data.frame(x=1, y=1), aes(x,y), shape = "\u2191", size=3.5) +
geom_point(data = data.frame(x=2, y=2), aes(x,y), shape = "\u2020", size=3.5) +
geom_point(data = data.frame(x=1.2, y=1.2), aes(x,y), shape = -10122, size=3.5, color="#FF7F00") +
geom_point(data = data.frame(x=1.4, y=1.4), aes(x,y), shape = -129322, size=3.5, color="#FB9A99") +
geom_point(data = data.frame(x=1.7, y=1.7), aes(x,y), shape = -128515, size=5, color="#1F78B4") +
ggtitle(sprintf('5\u03BCg'))
ggsave("temp.png", plot = test.plot, width = 80, height = 80, units = "mm")
#--- Refer to http://xahlee.info/comp/unicode_index.html to see more unicode character integers
pdf("UnicodeToPDF.pdf")
grid.arrange(
rasterGrob(
readPNG(
"temp.png",
native=F
)
)
)
dev.off()
file.remove("temp.png")

Resources