Mix ggplot graphs in multiple pages in pdf - r

Im trying to combine this graph i made in ggplot [![enter image description here][1]][1]
with a few more graphs (an example shown below) in a single PDF file. But the 1st graph is on one page, the next graph 2 is in page 2, graph 3 in page 3 and so on.
[![enter image description here][2]][2]
My problem is that i cant seem to combine the graphs in 1 pdf file as i keep getting an error where I cant open the PDF file.
Ive tried to modify the code ive seen here:
Printing multiple ggplots into a single pdf, multiple plots per page
but it cant seem to work
(this part is for the 4 graphs in 1 page)
pdf("plots.pdf", onefile = TRUE)
plot1 <- ggplot(data = FBMKLCI.df) +
theme_minimal() +
geom_line(aes(x = Date, y = PX_LAST., color =
PE)) +
scale_color_continuous(low = 'green', high='red') +
labs(y="", colour = "PE") +
theme(legend.position = 'bottom',
plot.title = element_text(colour = 'blue', face = 'bold'),
legend.key.width = unit(1, "cm")) +
ggtitle('FBMKLCI')
plot2<- ggplot(data = FBM70.df) +
theme_minimal() +
geom_line(aes(x = Date, y = PX_LAST., color =
PE)) +
scale_color_continuous(low = 'green', high='red') +
labs(y="",colour = "PE")+
theme(legend.position = 'bottom',
plot.title = element_text(colour = 'blue', face = 'bold'),
legend.key.width = unit(1, "cm")) +
ggtitle('FBM70')
plot3 <- ggplot(....
plot4<-...
grid.arrange(plot1, plot2, plot3, plot4, ncol=2)
(this part is for the graphs in the next pages)
p <- list()
for(i in 1:3) {
p[[i]] <- list()
p[[i]][[1]] <- ggplot(data = plot1) +
theme_minimal() +
facet_wrap(~Sector, nrow = 5, scales="free_y") +
geom_line(aes(x = Date, y = BEST_EPS.BEST_FPERIOD_OVERRIDE.1GY, color =
Sector)) +
theme(legend.position="none")
p[[i]][[2]] <- ggplot(data = plot2) +
theme_minimal() +
facet_wrap(~Sector, nrow = 5, scales="free_y") +
geom_line(aes(x = Date, y = eps.rev3mo, color = Sector)) +
theme(legend.position="none")
p[[i]][[3]] <- ggplot(data = plot3) +
theme_minimal() +
facet_wrap(~Sector, nrow = 5, scales="free_y") +
geom_line(aes(x = Date, y = eps.rev3mo, color = Sector)) +
theme(legend.position="none")
}
print(p)
dev.off()
I apologise in advance as this is my first time using ggplot2. Really appreciate and thanks in advance for the help.

Maybe this helps,
library(ggplot2)
library(gridExtra)
page1 <- replicate(4, ggplot(), simplify = FALSE)
other <- replicate(3, replicate(6, ggplot(), simplify = FALSE), simplify = FALSE)
pdf("multipage.pdf", width=6, height = 4)
grid.arrange(grobs = page1, ncol=2)
print(marrangeGrob(grobs = unlist(other, recursive = FALSE), ncol=3,nrow=2))
dev.off()

Related

Get all the legends on the top of the plot

I have a multiple plot within a plot, generated by ggpubr::ggarrange(). However the legends only appears for the first plot i.e., A and B. I wanted to get the legends for rest of the colours, C, D, E on the top. Setting common.legend = TRUE only gives the first two legends.
Thanks for the help!
library(ggpubr)
arranged_plot <- ggarrange(
plot_list[[1]] + rremove("ylab") + rremove("xlab") + rremove("x.text"),
plot_list[[2]] + rremove("ylab") + rremove("xlab") + rremove("axis.text"),
plot_list[[3]] + rremove("ylab") + rremove("xlab"),
plot_list[[4]] + rremove("ylab") + rremove("xlab") + rremove("y.text"),
labels = NULL, ncol = 2, nrow = 2,align = "hv",
font.label = list(size = 10, color = "black", face = "bold", family = NULL, position = "top"),
common.legend=TRUE)
I'm not sure how to do this with ggarrange, but if you're willing to look at other methods, here are two options:
Using patchwork (and collecting legends).
# sample data where each elem has cyl=4 and another cyl
mtcars$cyl <- factor(mtcars$cyl)
mtdat1 <- lapply(c(6, 8), function(CY) {
subset(mtcars, cyl %in% c(4, CY)) |>
transform(CY = CY)
})
plot_list <- lapply(mtdat1, function(dat) {
ggplot(dat, aes(mpg, disp, color = cyl)) +
geom_point() +
scale_color_manual(values = setNames(c("gray", "red", "blue"), c(4, 6, 8)), drop = FALSE)
})
library(patchwork)
plot_list[[1]] + plot_list[[2]] +
plot_layout(nrow = 1, guides = "collect") &
theme(legend.position = "top")
Facets.
# sample data, starting with `mtdat1` from above
mtdat2 <- do.call(rbind, args = mtdat1)
ggplot(mtdat2, aes(mpg, disp, color = cyl)) +
facet_wrap(~ CY) +
geom_point() +
scale_color_manual(values = setNames(c("gray", "red", "blue"), c(4, 6, 8)), drop = FALSE) +
theme(legend.position = "top")
If you prefer to not have the facet strips, we can remove those in a theme:
ggplot(mtdat2, aes(mpg, disp, color = cyl)) +
facet_wrap(~ CY) +
geom_point() +
scale_color_manual(values = setNames(c("gray", "red", "blue"), c(4, 6, 8)), drop = FALSE) +
theme(legend.position = "top", strip.text.x = element_blank())
I think there are two advantages to facets:
Simpler code, more efficient, allowing ggplot to handle everything in one step.
Since we don't explicitly free the scales (e.g., not doing scales="free"), the axes are all on the same scale, no need to explicitly control them. For comparisons as in your graph, this can be a big difference in visualizing the differences between levels. (Compare this plot with the first plot using patchwork, though those axis limits can easily be fixed as well.)

How do I repeat a symbol in the legend of a ggplot to gain a better view of the symbol?

I have just started the du Bois challenge as part of #tidytuesday, and am on challenge 1: Comparative Increase of White and Colored Population in Georgia
The original graph has the "WHITE" symbol with 4 dashes enter image description here, but when I replicate the plot, the legend only has 1 and a bit of the second dash.
How do I repeat the symbol in the legend to get 4 dashes? I don't need to increase the size, just the repetition
Try setting legend.key.width in theme:
library(ggplot2)
ggplot(df1, aes(x, y, linetype = f)) +
geom_line() +
scale_linetype_manual(values = c("solid", "dashed")) +
theme(legend.key.width = unit(1.5, "strwidth", "- - - - "))
Test data
set.seed(2021)
df1 <- data.frame(
x = c(1:10, 1:10),
y = c(cumsum(rnorm(10)), cumsum(rnorm(10))),
f = rep(c("A", "B"), each = 10)
)
Similar to the approach by #RuiBarradas but making use of guide_legend to set the keywidth you could achieve your desired result like so:
library(ggplot2)
ggplot(economics, aes(date)) +
geom_line(aes(y = psavert, linetype = "psavert")) +
geom_line(aes(y = uempmed, linetype = "uempmed")) +
scale_linetype_manual(values = c(psavert = 1, uempmed = 5)) +
guides(linetype = guide_legend(keywidth = unit(50, "pt"))) +
theme(legend.position = "bottom")

Alignment of y axis labels in faced_grid and ggplot?

By using ggplot and faced_grid functions I'm trying to make a heatmap. I have a categorical y axis, and I want y axis labels to be left aligned. When I use theme(axis.text.y.left = element_text(hjust = 0)), each panels' labels are aligned independently. Here is the code:
#data
set.seed(1)
gruplar <- NA
for(i in 1:20) gruplar[i] <- paste(LETTERS[sample(c(1:20),sample(c(1:20),1),replace = T) ],
sep="",collapse = "")
gruplar <- cbind(gruplar,anagruplar=rep(1:4,each=5))
tarih <- data.frame(yil= rep(2014:2019,each=12) ,ay =rep_len(1:12, length.out = 72))
gruplar <- gruplar[rep(1:nrow(gruplar),each=nrow(tarih)),]
tarih <- tarih[rep_len(1:nrow(tarih),length.out = nrow(gruplar)),]
grouped <- cbind(tarih,gruplar)
grouped$value <- rnorm(nrow(grouped))
#plot
p <- ggplot(grouped,aes(ay,gruplar,fill=value))
p <- p + facet_grid(anagruplar~yil,scales = "free",
space = "free",switch = "y")
p <- p + theme_minimal(base_size = 14) +labs(x="",y="") +
theme(strip.placement = "outside",
strip.text.y = element_text(angle = 90))
p <- p + geom_raster(aes(fill = value), na.rm = T)
p + theme(axis.text.y.left = element_text(hjust = 0, size=14))
I know that by putting spaces and using a mono-space font I can solve the problem, but I have to use the font 'Calibri Light'.
Digging into grobs isn't my favourite hack, but it can serve its purpose here:
# generate plot
# (I used a smaller base_size because my computer screen is small)
p <- ggplot(grouped,aes(ay,gruplar,fill=value)) +
geom_raster(aes(fill = value),na.rm = T) +
facet_grid(anagruplar~yil,scales = "free",space = "free",switch = "y") +
labs(x="", y="") +
theme_minimal(base_size = 10) +
theme(strip.placement = "outside",
strip.text.y = element_text(angle = 90),
axis.text.y.left = element_text(hjust = 0, size=10))
# examine ggplot object: alignment is off
p
# convert to grob object: alignment is unchanged (i.e. still off)
gp <- ggplotGrob(p)
dev.off(); grid::grid.draw(gp)
# change viewport parameters for left axis grobs
for(i in which(grepl("axis-l", gp$layout$name))){
gp$grobs[[i]]$vp$x <- unit(0, "npc") # originally 1npc
gp$grobs[[i]]$vp$valid.just <- c(0, 0.5) # originally c(1, 0.5)
}
# re-examine grob object: alignment has been corrected
dev.off(); grid::grid.draw(gp)
I guess one option is to draw the labels on the right-hand side, and move that column in the gtable,
p <-ggplot(grouped,aes(ay,gruplar,fill=value)) +
facet_grid(anagruplar~yil,scales = "free",space = "free",switch = "y") +
geom_raster(aes(fill = value),na.rm = T) +
theme_minimal(base_size = 12) + labs(x="",y="") +
scale_y_discrete(position='right') +
theme(strip.placement = "outside", strip.text.y = element_text(angle = 90))+
theme(axis.text.y.left = element_text(hjust = 0,size=14))
g <- ggplotGrob(p)
id1 <- unique(g$layout[grepl("axis-l", g$layout$name),"l"])
id2 <- unique(g$layout[grepl("axis-r", g$layout$name),"l"])
g2 <- gridExtra::gtable_cbind(g[,seq(1,id1-1)],g[,id2], g[,seq(id1+1, id2-1)], g[,seq(id2+1, ncol(g))])
library(grid)
grid.newpage()
grid.draw(g2)
This seems like a bug in ggplot2, or at least what I consider an undesirable / unexpected behavior. You may have seen the approach suggested here, which uses string padding on a mono-space font to achieve the alignment.
This is pretty hacky, but if you need to achieve alignment using a particular font, you might replace the axis labels altogether with geom_text. I have a mostly-working solution, but it is ugly, in that each step seems to break something else!
library(ggplot2); library(dplyr)
# To add a blank facet before 2014, I convert to character
grouped$yil = as.character(grouped$yil)
# I add some rows for the dummy facet, in year "", to use for labels
grouped <- grouped %>%
bind_rows(grouped %>%
group_by(gruplar) %>%
slice(1) %>%
mutate(yil = "",
value = NA_real_) %>%
ungroup())
p <- ggplot(grouped,
aes(ay,gruplar,fill=value)) +
geom_raster(aes(fill = value),na.rm = T) +
scale_x_continuous(breaks = 4*0:3) +
facet_grid(anagruplar~yil,
scales = "free",space = "free",switch = "y") +
theme_minimal(base_size = 14) +
labs(x="",y="") +
theme(strip.placement = "outside",
strip.text.y = element_text(angle = 90),
axis.text.y.left = element_blank(),
panel.grid = element_blank()) +
geom_text(data = grouped %>%
filter(yil == ""),
aes(x = -40, y = gruplar, label = gruplar), hjust = 0) +
scale_fill_continuous(na.value = "white")
p
(The last problem with this plot that I can see is that it shows an orphaned "0" on the x axis of the dummy facet. Need another hack to get rid of that!)

Add empty plots to facet, and combine with another facet

Using this SO solution I created a facet with two "empty" plots, with the aim of combining with another group of facet_wrap plots, as shown below. The purpose is to have two y-axis labels for different unit measurements. How can I make the grid layout look like the top image, which produces the arrangement I want, but not the axis labels? This was accomplished with plot_grid with individual plots. My current output does not scale correctly and overlaps the other plots, as seen in the second image, but provides the axis labels.
I have example data below, just copy and run the code to input it.
library(ggplot2)
library(grid)
library(cowplot)
clipboard <- readClipboard()
test.data <- read.table(file = "clipboard", sep = ",", header=TRUE)
test.data1 <- test.data[1:24, ]
test.data2 <- test.data[25:32, ]
testplot1 <- ggplot(test.data1, aes(Station, value)) +
geom_point() +
labs(x = "Stations", y = "Scale A") +
theme(legend.position = "none", legend.title = element_blank()) +
facet_wrap( ~ constituent, ncol = 3, scales = "free_y")
testplot2 <- ggplot(test.data2, aes(Station, value)) +
geom_point() +
labs(x = "Stations", y = "Scale B") +
theme(legend.position = "none", legend.title = element_blank(), axis.title.y = element_text(hjust = 0.2)) +
facet_wrap( ~ constituent, ncol = 1, scales = "free_y")
blankplots <- ggplotGrob(testplot2)
rm_grobs <- blankplots$layout$name %in% c("panel-1-1", "panel-2-1", "strip-t-1-1", "strip-t-1-2")
blankplots$grobs[rm_grobs] <- NULL
blankplots$layout <- blankplots$layout[!rm_grobs, ]
grid.newpage()
emptygrids <- grid.draw(blankplots)
plot_grid(emptygrids, MPLOOplot1)
Example date is below:
Station,constituent,value
A1,A,1
B1,A,1
A1,B,2
B1,B,2
A1,C,3
B1,C,3
A1,D,4
B1,D,4
A1,E,5
B1,E,5
A1,F,6
B1,F,6
A1,G,7
B1,G,7
A1,H,8
B1,H,8
A1,I,9
B1,I,9
A1,J,10
B1,J,10
A1,K,11
B1,K,11
A1,L,1.4
B1,L,1.4
A1,Blank1,NA
B1,Blank1,NA
A1,Blank2,NA
B1,Blank2,NA
A1,XX,0.52
B1,XX,0.52
A1,YY,0.355
B1,YY,0.355
I'm not sure I understand exactly what you're trying to do, so let me know if this is what you had in mind. I wasn't sure what you wanted colour to be mapped to, so I just used constituent for this example.
library(gridExtra)
library(ggplot2)
library(dplyr)
library(cowplot)
theme_set(theme_classic())
testplot1 <- ggplot(test.data1, aes(Station, value, colour=constituent)) +
geom_point() +
labs(x = "Stations", y = "Scale A") +
theme(legend.title = element_blank()) +
facet_wrap( ~ constituent, ncol = 3, scales = "free_y") +
guides(colour=guide_legend(ncol=2))
testplot2 <- ggplot(test.data2 %>% filter(!grepl("Blank", constituent)),
aes(Station, value, colour=constituent)) +
geom_point() +
labs(x = "Stations", y = "Scale B") +
theme(legend.title = element_blank(),
axis.title.y = element_text(hjust = 0.2)) +
facet_wrap( ~ constituent, ncol = 1, scales = "free_y")
leg1 = get_legend(testplot1)
leg2 = get_legend(testplot2)
testplot1 = testplot1 + guides(colour=FALSE)
testplot2 = testplot2 + guides(colour=FALSE)
Now we lay out the plots and legends with grid.arrange. This requires some manual tweaking of the heights and widths.
grid.arrange(
arrangeGrob(
arrangeGrob(nullGrob(), leg2, leg1, nullGrob(), ncol=4, widths=c(1,4,4,1)),
testplot2, ncol=1, heights=c(4.2,5)
),
testplot1, ncol=2, widths=c(1.1,3))

adding a border around a grob (R) [duplicate]

I'm using the code below:
# Libs
require(ggplot2); require(gridExtra); require(grid)
# Generate separate charts
chrts_list_scts <- list()
# Data
data("mtcars")
# A
chrts_list_scts$a <- ggplot(mtcars) +
geom_point(size = 2, aes(x = mpg, y = disp,
colour = as.factor(cyl))) +
geom_smooth(aes(x = mpg, y = disp),
method = "auto") +
xlab("MPG") +
ylab("Disp") +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.position = "none")
# B
chrts_list_scts$b <- ggplot(mtcars) +
geom_point(size = 2, aes(x = mpg, y = drat,
colour = as.factor(cyl))) +
geom_smooth(aes(x = mpg, y = drat),
method = "auto") +
xlab("MPG") +
ylab("Drat") +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.position = "none")
# C
chrts_list_scts$c <- ggplot(mtcars) +
geom_point(size = 2, aes(x = mpg, y = qsec,
colour = as.factor(cyl))) +
geom_smooth(aes(x = mpg, y = qsec),
method = "auto") +
xlab("MPG") +
ylab("QSEC") +
guides(colour = guide_legend(title = "cyl")) +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.position = "bottom",
legend.key = element_rect(colour = NA))
# Arrange grid
png(filename = "chrts.PNG", width = 6,
height = 10, units = 'in', res = 300)
title_text <- c("mtcars")
chrts_list_scts$all_scts <- grid.arrange(chrts_list_scts$a,
chrts_list_scts$b,
chrts_list_scts$c,
top =
textGrob(label = title_text,
gp = gpar(
fontsize = 14,
font = 2)))
dev.off()
rm(title_text)
To generate the following chart:
I'm interested in adding border around that chart, as in the picture below:
Attempts
I tried to address this request via adding polygonGrob in the code:
chrts_list_scts$all_scts <- grid.arrange(chrts_list_scts$dep_work,
chrts_list_scts$chld_work,
chrts_list_scts$pens,
polygonGrob(x = c(0,0.5,1.05),
y = c(0,0.5,1.05)
),
top =
textGrob(label = title_text,
gp = gpar(
fontsize = 14,
font = 2)))
but this generates a pointless chart with one line across in the bottom. I had a look at the seeming similar discussion on SO but it wasn't clear to me how to arrive at a working solution.
Side requirements
In addition to generating the border, I would like to:
Be able to exercise some control over the border aesthetics, like changing size and colour of the border.
Ideally, I would like to encapsulate this solution within the arrange.grid call. So at the object chrts_list_scts$all_scts has all elements including charts and neat border around all of them.
I will be happy to accept solutions that address the major requirements with respect to the border only, if there is a suggested solution that matches the remaining two points it will be even nicer.
1) Using the iris example (but further simplified) from the link provided in the question just add the last line. Modify the gpar(...) components (and possibly the width and height) to get different aesthetics. (This is not encapsulated in the grid.arrange call.)
library(ggplot2)
library(grid)
library(gridExtra)
g <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point()
grid.arrange(g, g, ncol=2)
# next line adds border
grid.rect(width = .98, height = .98, gp = gpar(lwd = 2, col = "blue", fill = NA))
(continued after plot)
2) This is a variation of solution (1) in which on the plus side encapsulates both the graphics and border in the gt gTree by creating grobs to hold each. On the other hand it does involve some additional complexity:
grid.newpage()
ga <- arrangeGrob(g, g, ncol = 2)
gb <- rectGrob(height = .98, width = .98, gp = gpar(lwd = 2, col = "blue", fill = NA)) # border, no fill
gt <- gTree(children = gList(ga, gb))
grid.draw(gt)
you can add a rectGrob to the gtable
grid.draw(gtable::gtable_add_grob(arrangeGrob(g, g, ncol=2),
rectGrob(gp=gpar(lwd=5, fill=NA)), 1, 1, 1, 2))
NOTE: fill=NA or fill='transparent' is required otherwise the rectangle can mask the objects below it.

Resources