Increase plot size (width) in ggplot2 - r

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

Related

Set white background with plot that includes marginals (ggExtra + ggplot2)

I want to generate a PDF with many plots, one per page. These plots contain marginal distributions on the sides, generated with ggExtra:
library(ggplot2)
library(ggExtra)
set.seed(1)
pdf("example.pdf", width = 5, height=5, bg = "white")
for(i in 1:10){
plot.df <- data.frame(x = rnorm(1000), y = rnorm(1000))
p1 <- ggplot(plot.df, aes(x = x, y = y)) +
geom_point() +
ggtitle(i)
p1 <- ggMarginal(p1)
plot(p1)
}
dev.off()
However, the plots appear with a grey grid background instead of white background (see below). How can I make all the background white? Also, the output PDF contains a blank page at the beginning. How can avoid it being created?
You need to change the theme of the plot. You can choose for example theme_void(), or make your own using theme(), and add it to your plot.
p1 <- ggplot(plot.df, aes(x = x, y = y)) +
geom_point() +
ggtitle(i) +
theme_void()
Example of theme_void() :

How do you force Rmarkdown plots to be Square instead of Rectangle?

I have a Generalized Linear Model (GLM) that I'm plotting diagnostics for using the glm.diag.plots function in the MASS package. But it tends to plot rectangular instead of square, which is very ugly for publication.
Below is some sample code that shows the problem in an .Rmd file. In Rstudio, you can just drag the window around until it's square, but not possible in Rmarkdown documents, and I'd like to enforce square manually.
I checked in the ggplot documentation for ways to enforce square plotting, but could not find anything. glm.diag.plot() appears to use split.screen(), which doesn't provide any documentation for enforcing aspect ratios, either.
#rawr's comment is spot-on; this is a knitr/markdown issue, not glm.diag or ggplot or anything else. All you need to do is specify the desired height and width of the output (in inches, by default) using fig.width and fig.height.
It looks like you are using glm.diag.plots from package boot to acquire plots.
You could recreate them using ggplot if you wish. Here is an example:
some model:
data(anorexia, package = "MASS")
anorex.1 <- glm(Postwt ~ Prewt + Treat + offset(Prewt),
family = gaussian, data = anorexia)
the glm.diag.plots output
library(boot)
glm.diag.plots(anorex.1)
To create each plot in ggplot first get an object from glm.diag.plots
z <- glm.diag.plots(anorex.1, ret = T)
then plot each plot:
library(ggplot2)
plot1 <- ggplot(data.frame(x = predict(anorex.1),
y = z$res))+
geom_point(aes(x, y)) +
xlab("Linear predictor") +
ylab("Residuals") +
theme_bw()+
theme(aspect.ratio=1)
plot2 <- ggplot(data.frame(x = qnorm(ppoints(length(z$rd)))[rank(z$rd)],
y = z$rd)) +
geom_point(aes(x, y)) +
xlab("Ordered deviance residuals") +
ylab("Quantiles of standard normal") +
geom_abline(intercept = 0, slope = 1, lty =2) +
theme_bw()+
theme(aspect.ratio=1)
plot3 <- ggplot(data.frame(x = z$h/(1-z$h),
y = z$cook)) +
geom_point(aes(x, y)) +
xlab("h/(h-1)") +
ylab("Cook statistic") +
theme_bw()+
theme(aspect.ratio=1)
plot4 <- ggplot(data.frame(x = 1:length(z$cook),
y = z$cook)) +
geom_point(aes(x, y)) +
xlab("Case") +
ylab("Cook statistic") +
theme_bw()+
theme(aspect.ratio=1)
then combine them
library(cowplot)
plot_grid(plot1, plot2, plot3, plot4, ncol = 2)
Now you can customize each plot the way you wish.

Crop out ggplot2 whitespace around plot

Is there a way to remove the white space surrounding a ggplot2 plot when the shape has been changed using coord_fixed()? I would like the white space above and below to be cropped away so that only the plotting area and axis labels remain. I am rendering the plot output in an R markdown file without saving.
p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
p + coord_fixed(ratio = 1)
The code below produces the following plot:
When you use:
ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
coord_fixed(ratio = 1) +
ggsave('plot.jpg', width = 6, height = 1.5, dpi = 300)
You get a plot with less white space:
Another option could be to use the png or jpeg device:
p <- ggplot(mtcars, aes(mpg, wt)) +
geom_point() +
coord_fixed(ratio = 1)
jpeg('plot.jpg', width = 600, height = 150)
p
dev.off()
If you are looking for a solution which also works in R markdown (i.e. output as PDF/HTML), this solved it for me: first set the aspect ratio and then remove the additional margin on the top via the theme() settings.
library(ggplot2)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, shape = Species, color = Species)) +
geom_point(size = 5) +
coord_fixed(ratio = 1/2) +
theme(plot.margin=unit(c(-0.30,0,0,0), "null")) # remove margin around plot
See also this blog post for more details.
Session info:
MacOs 10.13.6, R 3.6.3, ggplot2_3.3.1

Multiple "Top" textGrob Titles

The following is a simple example of my issue (please forgive the repetitive plots - can't use my actual data)
Example:
#packages
library(grid)
library(gridExtra)
library(ggplot2)
#simple plot
p <- ggplot(mtcars, aes(wt,mpg))
# setting-up grid of plots...2 columns by 4 rows
sample <- grid.arrange(p + geom_point()+labs(title="Sample \nTitle One"),
p + geom_point()+labs(title="Sample \nTitle Two"),
p + geom_point(),
p + geom_point(),
p + geom_point(),
p + geom_point(),
p + geom_point(),
p + geom_point(),
ncol = 2)
Output:
Issue: The top two plots have been compressed. I attempted to use the textGrob, like follows:
top = textGrob("Sample Title One",hjust = 1,gp = gpar(fontfamily = "CM Roman", size = 12))
But, I am not seeing a way to incorporate two separate titles. I have yet to try using cowplot, which might be a more reasonable way to go, but was curious if there was a way to do this using textGrob.
Thanks for your time!
As stated by user20650, you can do the following:
grid.arrange(arrangeGrob(p,p,p,p,top=textGrob("Sample Title One"),
ncol=1), arrangeGrob(p,p,p,p,top=textGrob("Sample Title Two"), ncol=1),
ncol = 2)
To get the following:

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

Resources