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
Related
I have the facet_wrap function to make multiple graphs (n=~51) but they all appear on one page. Now after searching, I found out that ggplot2 can't place graphs on multiple pages.
Is there a way to do this? I looked at this question (Multiple graphs over multiple pages using ggplot) and tried out the code, with little success.
Here is my code for my graphs, it produces ~51 graphs on one page, making them very small and hard to see, if I could print this to 1 graph per page in a pdf, that would be great:
ggplot(indbill, aes(x = prey, y = weight), tab) +
geom_polygon(aes(group = load, color = capture), fill = NA, size = 0.75) +
facet_wrap(~ individual) +
theme(axis.ticks.x = element_blank(),
axis.text.x = element_text(size=rel(0.5)),
axis.ticks.y = element_blank(),
axis.text.y = element_blank()) +
xlab("") + ylab("") +
guides(color = guide_legend(ncol=2)) +
coord_radar()
If someone could write up a little code and explain it to me, that would be great.
There are multiple ways to do the pagination: ggforce or gridExtra::marrangeGrob. See also this answer for another example.
ggforce:
library(ggplot2)
# install.packages("ggforce")
library(ggforce)
# Standard facetting: too many small plots
ggplot(diamonds) +
geom_point(aes(carat, price), alpha = 0.1) +
facet_wrap(~cut:clarity, ncol = 3)
# Pagination: page 1
ggplot(diamonds) +
geom_point(aes(carat, price), alpha = 0.1) +
facet_wrap_paginate(~cut:clarity, ncol = 3, nrow = 3, page = 1)
# Pagination: page 2
ggplot(diamonds) +
geom_point(aes(carat, price), alpha = 0.1) +
facet_wrap_paginate(~cut:clarity, ncol = 3, nrow = 3, page = 2)
# Works with grid as well
ggplot(diamonds) +
geom_point(aes(carat, price), alpha = 0.1) +
facet_grid_paginate(color~cut:clarity, ncol = 3, nrow = 3, page = 4)
gridExtra:
# install.packages("gridExtra")
library(gridExtra)
set.seed(123)
pl <- lapply(1:11, function(.x)
qplot(1:10, rnorm(10), main=paste("plot", .x)))
ml <- marrangeGrob(pl, nrow=2, ncol=2)
## non-interactive use, multipage pdf
## ggsave("multipage.pdf", ml)
## interactive use; calling `dev.new` multiple times
ml
Created on 2018-08-09 by the reprex package (v0.2.0.9000).
One option is to just plot, say, six levels of individual at a time using the same code you're using now. You'll just need to iterate it several times, once for each subset of your data. You haven't provided sample data, so here's an example using the Baseball data frame:
library(ggplot2)
library(vcd) # For the Baseball data
data(Baseball)
pdf("baseball.pdf", 7, 5)
for (i in seq(1, length(unique(Baseball$team87)), 6)) {
print(ggplot(Baseball[Baseball$team87 %in% levels(Baseball$team87)[i:(i+5)], ],
aes(hits86, sal87)) +
geom_point() +
facet_wrap(~ team87) +
scale_y_continuous(limits=c(0, max(Baseball$sal87, na.rm=TRUE))) +
scale_x_continuous(limits=c(0, max(Baseball$hits86))) +
theme_bw())
}
dev.off()
The code above will produce a PDF file with four pages of plots, each with six facets to a page. You can also create four separate PDF files, one for each group of six facets:
for (i in seq(1, length(unique(Baseball$team87)), 6)) {
pdf(paste0("baseball_",i,".pdf"), 7, 5)
...ggplot code...
dev.off()
}
Another option, if you need more flexibility, is to create a separate plot for each level (that is, each unique value) of the facetting variable and save all of the individual plots in a list. Then you can lay out any number of the plots on each page. That's probably overkill here, but here's an example where the flexibility comes in handy.
First, let's create all of the plots. We'll use team87 as our facetting column. So we want to make one plot for each level of team87. We'll do this by splitting the data by team87 and making a separate plot for each subset of the data.
In the code below, split splits the data into separate data frames for each level of team87. The lapply wrapper sequentially feeds each data subset into ggplot to create a plot for each team. We save the output in plist, a list of (in this case) 24 plots.
plist = lapply(split(Baseball, Baseball$team87), function(d) {
ggplot(d, aes(hits86, sal87)) +
geom_point() +
facet_wrap(~ team87) +
scale_y_continuous(limits=c(0, max(Baseball$sal87, na.rm=TRUE))) +
scale_x_continuous(limits=c(0, max(Baseball$hits86))) +
theme_bw() +
theme(plot.margin=unit(rep(0.4,4),"lines"),
axis.title=element_blank())
})
Now we'll lay out six plots at time in a PDF file. Below are two options, one with four separate PDF files, each with six plots, the other with a single four-page PDF file. I've also pasted in one of the plots at the bottom. We use grid.arrange to lay out the plots, including using the left and bottom arguments to add axis titles.
library(gridExtra)
# Four separate single-page PDF files, each with six plots
for (i in seq(1, length(plist), 6)) {
pdf(paste0("baseball_",i,".pdf"), 7, 5)
grid.arrange(grobs=plist[i:(i+5)],
ncol=3, left="Salary 1987", bottom="Hits 1986")
dev.off()
}
# Four pages of plots in one PDF file
pdf("baseball.pdf", 7, 5)
for (i in seq(1, length(plist), 6)) {
grid.arrange(grobs=plist[i:(i+5)],
ncol=3, left="Salary 1987", bottom="Hits 1986")
}
dev.off()
something like :
by(indbill, indbill$individual, function (x){
ggplot(x, aes(x = prey, y = weight), tab) +
geom_polygon(aes(group = load, color = capture), fill = NA, size = 0.75) +
theme(axis.ticks.x = element_blank(),
axis.text.x = element_text(size=rel(0.5)),
axis.ticks.y = element_blank(),
axis.text.y = element_blank()) +
xlab("") + ylab("") +
guides(color = guide_legend(ncol=2)) +
coord_radar()
}
I have a list of jitter plots created using geom_jitter() method. How can I print the list as an animated GIF? Although, I can easily print them as a pdf.
I saw some posts where users have created the animation using a function, but I don't have a function, just a list.
p1 <- ggplot(Test, aes(x=factor(Wavelength, level = level_order), y=Reflectance, color=SDS.y)) +
geom_jitter(aes(color=SDS.y), alpha = 0.3, width = 0.3) +
labs(title = "Threshold (Healthy = 0-5, Diseased = 6-100)", x = "Wavelength", y = "Reflectance") +
scale_y_continuous(limits = c(0.5, 1)) +
theme_bw(base_size = 16) +
scale_color_manual(values=c("purple", "red3")) +
facet_grid(Rotation~Date)
#Printing all plots to 1 pdf file
Plots = list(p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15,p16,p17,p18,p19)
pdf("Jitter Plots.pdf", width = 25, height = 8.5)
Plots
dev.off()
Here is the sample animated GIF that I am expecting. However, I created this simply by converting pdf to GIF.
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 produce nine ggplots within a for loop and subsequently arrange those plots using grid.arrange:
plot_list <- list()
for(i in c(3:ncol(bilanz.vol))) {
histogram <- ggplot(data = bilanz.vol, aes(x = bilanz.vol[,i])) +
geom_histogram() +
scale_x_log10() +
ggtitle(paste(varnames[i]))
# ggsave(filename = paste("Graphs/", vars[i], ".png", sep = ""), width = 16, height = 12, units = "cm")
plot_list <- c(plot_list, list(histogram))
}
library(gridExtra)
png(filename = "Graphs/non-mfi.png", width = 1280, height = 960, units = "px")
do.call(grid.arrange, c(plot_list, list(ncol = 3)))
dev.off()
The code itself works fine and there are no errors. But for some reason I do not understand, the grid shows the same (last) histogram nine times. Still, each plot shows the correct title.
Interestingly, when I uncomment the ggsave line in the code above, each plot is saved correctly (separately) and shows the expected histogram.
Any ideas?
The reason is that ggplot does not evaluate the expression in the aes call before it is used (so I believe at least), it just sets up the plot and stores the data inside of it. In you case "the data" is the entire data frame bilanz.vol and since i = ncol(bilanz.vol) after the for loop completes the expression bilanz.vol[,i] will evaluate to the same thing for all plot objects.
To make it work you could do this, which makes sure all plot objects contains different data sets my.data.
my.data <- data.frame(x = bilanz.vol[,i])
histogram <- ggplot(data = my.data, aes(x = x)) +
geom_histogram() +
scale_x_log10() +
ggtitle(paste(varnames[i]))
Below is a plot that I want to include in a paper. The problem is the width of my plot which is to small (that make x-axix not readable at all)
Here is the ggplot2 code myCode.r :
require("ggplot2")
all <- read.csv(file="benchmark/bench.query.csv", head=TRUE, sep=";")
w <- subset(all, query %in% c("sort.q1", "sort.q2", "sort.q3", "sort.q4", "sort.q5"))
w$rtime <- as.numeric(sub(",", ".", w$rtime, fixed=TRUE))
p <- ggplot(data=w, aes(x=query, y=rtime, colour=triplestore, shape=triplestore))
p <- p + scale_shape_manual(values = 0:length(unique(w$triplestore)))
p <- p + geom_point(size=4)
p <- p + geom_line(size=1,aes(group=triplestore))
p <- p + labs(x = "Requêtes", y = "Temps d'exécution (log10(ms))")
p <- p + scale_fill_continuous(guide = guide_legend(title = NULL))
p <- p + facet_grid(trace~type)
p <- p + theme_bw()
ggsave(file="bench_query_sort.pdf")
print (p)
I've look around to see how to enlarge the plot, but I found nothing.
Any idea about what to add/delete/modify in my code ?
Inside a Jupyter notebook I found the following helpful:
# Make plots wider
options(repr.plot.width=15, repr.plot.height=8)
Probably the easiest way to do this, is by using the graphics devices (png, jpeg, bmp, tiff). You can set the exact width and height of an image as follows:
png(filename="bench_query_sort.png", width=600, height=600)
ggplot(data=w, aes(x=query, y=rtime, colour=triplestore, shape=triplestore)) +
scale_shape_manual(values = 0:length(unique(w$triplestore))) +
geom_point(size=4) +
geom_line(size=1,aes(group=triplestore)) +
labs(x = "Requêtes", y = "Temps d'exécution (log10(ms))") +
scale_fill_continuous(guide = guide_legend(title = NULL)) +
facet_grid(trace~type) +
theme_bw()
dev.off()
The width and height are in pixels. This is especailly useful when preparing images for publishing on the internet. For more info, see the help-page with ?png.
Alternatively, you can also use ggsave to get the exact dimensions you want. You can set the dimensions with:
ggsave(file="bench_query_sort.pdf", width=4, height=4, dpi=300)
The width and height are in inches, with dpi you can set the quality of the image.
If you are using RMD(R Markdown) this would be the easiest way to define width and height.
```{r fig.align="center", echo = FALSE,fig.width = 14}
<write the code for your plot here>
```
Note: options() not worked for me so I used this method