Legend overlaps the plot in patchwork when using guide_area - r

guides = "collect" does its job but it locates the legend in a way that it overlaps the plot. I would like it to be placed right in the middle of the empty bottom right corner, but it appears to be difficult since theme(legend.position = c(X,Y)) does not work with patchwork
Illustration of the issue:
This is the code I have for assembling 4 graphs I have using patchwork. Pretty sure there is a more elegant way to use theme() but I am quite new to patchwork and it worked for me so far, except for the legend positioning.
A similar issue was resolved here but it does not seem to help in my case.
#first panel
s_wpanels_final <- (dots & theme_bw() & theme(axis.title.x =
element_blank(), panel.grid.minor.y = element_blank())) +
#second panel
(g_box_tmax & theme_bw() & theme(axis.text.x=element_blank(),
axis.ticks.x=element_blank(), panel.grid.minor.y = element_blank(),
axis.text.y=element_blank(), axis.ticks.y=element_blank(),
axis.title.x = element_blank(), legend.position = "none")) +
#third panel
(g_box_t0 & theme_bw() & theme(axis.text.x=element_blank(),
axis.ticks.x=element_blank(), panel.grid.minor.y = element_blank(),
axis.text.y=element_blank(), axis.ticks.y=element_blank(),
axis.title.x = element_blank(), legend.position = "none")) +
#fourth panel
(tmax_box & theme_bw() & theme(axis.text.x=element_blank(),
axis.ticks.x=element_blank(), axis.text.y=element_blank(),
axis.ticks.y=element_blank(), axis.title.y = element_blank(),
legend.position = "none")) +
guide_area()+
plot_layout(ncol=3, guides = "collect", widths=c(6,1,1), heights=c(6,1)) &
theme(legend.direction = "vertical", legend.box = "horizontal")

There are two issues with your code. First using + to glue your plots together and setting ncol=3 will place the guide_area in the second column of the second row. To center the legend I would suggest to use the design argument to specify the layout of the plot. Second, while the plot panels will adjust to the space set via the height and width arguments and the size of your plotting device, the legend will not, i.e. if the legend will not fit into the space given it will overlap with the surrounding panels. To fix that I would suggest to increase the widths of the second and third columns and the height of the second row. But as I said this also depends on the size of the plotting device.
Using some fake example plot based on mtcars(see below) let's first reproduce your issue:
library(ggplot2)
library(patchwork)
list(
dots,
g_box_tmax,
g_box_t0,
tmax_box,
guide_area()
) |>
wrap_plots() +
plot_layout(guides = "collect", widths = c(6, 1, 1), heights = c(6, 1), ncol = 3) &
theme(legend.direction = "vertical", legend.box = "horizontal")
However, specifying the layout via the design argument and increasing the height of the second row as well as the widths of the second and third columns works fine and centers the legend in the guide area:
design <-
"
ABC
DEE
"
list(
dots,
g_box_tmax,
g_box_t0,
tmax_box,
guide_area()
) |>
wrap_plots() +
plot_layout(guides = "collect", widths = c(6, 1.5, 1.5), heights = c(6, 1.5), design = design) &
theme(legend.direction = "vertical", legend.box = "horizontal")
PLOTS
dots <- ggplot(mtcars, aes(mpg, hp, color = factor(cyl), size = qsec)) +
geom_point() +
theme_bw() +
theme(
axis.title.x = element_blank(),
panel.grid.minor.y = element_blank()
)
g_box_tmax <- g_box_t0 <- ggplot(mtcars, aes(factor(cyl), hp, fill = factor(cyl))) +
geom_boxplot() +
theme_bw() +
theme(
axis.text.x = element_blank(),
axis.ticks.x = element_blank(), panel.grid.minor.y = element_blank(),
axis.text.y = element_blank(), axis.ticks.y = element_blank(),
axis.title.x = element_blank(), legend.position = "none"
)
tmax_box <- ggplot(mtcars, aes(mpg, factor(cyl), fill = factor(cyl))) +
geom_boxplot() +
theme_bw() +
theme(
axis.text.x = element_blank(),
axis.ticks.x = element_blank(), axis.text.y = element_blank(),
axis.ticks.y = element_blank(), axis.title.y = element_blank(),
legend.position = "none"
)

What causes the legend box (which is too big for the plot dimension) to be positioned there, is probably some quite clever patchwork code, and is related to guide_area (therefore my question title edit).
The below is a slightly unsatisfactory, but effective hack to modify the position. It's a bit of a trial and error. Simply give a negative margin to the legend box to the right and it will "drag" the box accordingly.
I've removed all the legend.position = "none" from your plots as this is not necessary with guides = "collect"
library(ggplot2)
library(patchwork)
p1 <- ggplot(iris) + geom_point(aes(Sepal.Length, Sepal.Width, color = Species, size = Petal.Length))
p2 <- ggplot(iris) + geom_point(aes(Sepal.Length, Sepal.Width, color = Species, size = Petal.Length))
p3 <- ggplot(iris) + geom_point(aes(Sepal.Length, Sepal.Width, color = Species, size = Petal.Length))
p4 <- ggplot(iris) + geom_point(aes(Sepal.Length, Sepal.Width, color = Species, size = Petal.Length))
p1 + p2 + p3 + p4 +
guide_area()+
plot_layout(ncol=3, guides = "collect", widths=c(6,1,1), heights=c(6,1)) &
theme(legend.direction = "vertical", legend.box = "horizontal",
legend.box.margin = margin(r = -1, unit = "in"))

Related

Can you get the axis of the marginal densities to line up with the axis of the scatter plot

Hi I have the plot below and the marginal density plots are slightly off. They do not line up to the x and y axis of the scatter plot so interpretation can be a bit misleading.
I can sort of play with these lines of code to try and get the margins to align for rthe marginal plots but it is very manual and frustrating.
theme0(plot.margin = unit(c(1,0,0,2.2),"lines"))
theme0(plot.margin = unit(c(0,1,1.2,0),"lines"))
Is there a way to automatically find the right margins to pass to theme0(plot.margin = unit(c(0,1,1.2,0),"lines") so that no manual work needs to be done to line up the margins? Thank you.
library(ggplot2)
library(gridExtra)
set.seed(42)
DF <- data.frame(x=rnorm(100,mean=c(1,5)),y=rlnorm(100,meanlog=c(8,6)),group=1:2)
DF
## Scatter plot
p1 <- ggplot(DF,aes(x=x,y=y)) + geom_point() +
scale_x_continuous(expand=c(0.02,0)) +
scale_y_continuous(expand=c(0.02,0)) +
theme_bw() +
theme(legend.position="none",plot.margin=unit(c(0,0,0,0),"points")) # ggplot(DF,aes(x=x,y=y,colour=factor(group))) color the gorup
theme0 <- function(...) theme( legend.position = "none",
panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.margin = unit(0,"null"),
axis.ticks = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.ticks.length = unit(0,"null"),
axis.ticks.margin = unit(0,"null"),
panel.border=element_rect(color=NA),...)
### DENSITY OF X
p2 <- ggplot(DF,aes(x=x, fill="blue")) +
geom_density(alpha=0.5) +
scale_x_continuous(breaks=NULL,expand=c(0.02,0)) +
scale_y_continuous(breaks=NULL,expand=c(0.02,0)) +
theme_bw() +
theme0(plot.margin = unit(c(1,0,0,2.2),"lines")) # to color group ggplot(DF,aes(x=x,colour=factor(group),fill=factor(group)))
### DENSITY OF Y
p3 <- ggplot(DF,aes(x=y, fill = "red")) +
geom_density(alpha=0.5) +
coord_flip() +
scale_x_continuous(labels = NULL,breaks=NULL,expand=c(0.02,0)) +
scale_y_continuous(labels = NULL,breaks=NULL,expand=c(0.02,0)) +
theme_bw() +
theme0(plot.margin = unit(c(0,1,1.2,0),"lines")) # color group ggplot(DF,aes(x=y,colour=factor(group),fill=factor(group)))
grid.arrange(arrangeGrob(p2,ncol=2,widths=c(3,1)),
arrangeGrob(p1,p3,ncol=2,widths=c(3,1)),
heights=c(1,3))

In ggplot2 and facet_wrap, how to remove all margins and padding yet keep strip.text?

This might primarily be a result of me misunderstanding how panel.margin = unit(...) works in the theme() function...but I'm unable to customize margins in facet_wrap the way that I'd like. Basically, I want a facet_grid that looks like this, with facet text (i.e. strip.text) inset in each facet and no spcaing between each facet:
(I've left in the pink borders to show the dimensions of each facet)
So here's the code so far.
To set up the data and plot:
library(ggplot2)
library(grid)
p <- ggplot() +
geom_bar(data = mtcars, aes(x = cyl, y = qsec), stat = 'identity') +
facet_wrap( ~ carb, ncol = 3)
mytheme <- theme_minimal() + theme(
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
panel.margin = unit(0, "lines"),
panel.border = element_rect(colour = rgb(1.0, 0, 0, 0.5), fill=NA, size=1)
)
The standard plot
p + mytheme
Removing the strip.text completely
p + mytheme + theme(strip.text = element_blank())
Adding the strip.text and insetting it
p + mytheme +
theme(strip.text = element_text(size = rel(3.0), vjust = -4.0))
The re-inclusion of strip.text (and the increased relative size) increases the vertical margin between the two rows. So at this point, I don't know how to close the vertical gap between the top and bottom rows.
Too much negative margin
p + mytheme +
theme(strip.text = element_text(size = rel(3.0), vjust = -4.0),
panel.margin = unit(c(-2, -2), "lines"))
So how do I target just the panel.margin between the two rows?
Edit: Additional information. The space between the rows appears to be strip.background:
p + mytheme +
theme(strip.text = element_text(size = rel(3.0), vjust = -4.0),
panel.margin = unit(-1, "lines"),
strip.background = element_rect(fill = rgb(0, 1.0, 0, 0.2)))
Among the list of possible arguments to theme(), there is not only panel.margin ("margin around facet panels (unit)", see ?theme), but conveniently, you can also access one of the axes at a time, with panel.margin.x and panel.margin.y respectively ("horizontal/vertical margin around facet panels (unit; inherits from panel.margin)").
Therefore, while decreasing the margin below zero feels a bit like a hack, something like the following will do the job (you might have to adjust the value a little - unit(-2, "lines") worked best for me):
p + theme(strip.text = element_text(size = rel(3.0), vjust = -4.0),
panel.margin.y = unit(-2, "lines"))
If you use strip.text = element_blank(), then you should probably use panel.margin.y = unit(-0.5, "lines").

ggplot2 & facet_wrap - eliminate vertical distance between facets

I'm working with some data that I want to display as a nxn grid of plots. Edit: To be more clear, there's 21 categories in my data. I want to facet by category, and have those 21 plots in a 5 x 5 square grid (where the orphan is by itself on the fifth row). Thus facet_wrap instead of facet_grid.
I've got the following code written up for doing it (using the good old iris data set for my reproducible example):
library(ggplot2)
library(grid)
cust_theme <- theme_bw() + theme(legend.position="none",
axis.title = element_blank(), axis.ticks = element_blank(),
axis.text = element_blank(), strip.text = element_blank(),
strip.background = element_blank(), panel.margin = unit(0, "lines"),
panel.border = element_rect(size = 0.25, color = "black"),
panel.grid = element_blank())
iris.plot <- ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_point() + cust_theme + facet_wrap( ~ Species, ncol = 2) +
labs(title = "Irises by species")
This gives me ALMOST what I want, but not quite:
I've still got a tiny strip of space between the top row of plots and the bottom row. I'd like to get rid of that entirely, but panel.margin is obviously not doing it. Is there a way to do this?
This might be a little late, but panel.marginis now deprecated. Inside theme use panel.spacing. To eliminate the spacing between the facets then load the grid package and use panel.spacing = unit(0, "lines")
Change the panel.margin argument to panel.margin = unit(c(-0.5,0-0.5,0), "lines"). For some reason the top and bottom margins need to be negative to line up perfectly. Here is the result:
You can also edit the grobs directly:
library(ggplot2)
library(grid)
g <- ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) +
geom_point() +
facet_wrap( ~ Species, ncol = 2) +
labs(title = "Irises by species") +
theme_bw() +
theme(panel.margin = unit(0, "lines")) +
theme(plot.margin = unit(c(0,0,0,0), "lines")) +
theme(strip.background = element_blank()) +
theme(plot.background = element_blank()) +
theme(strip.text = element_blank()) +
theme(axis.ticks.margin = unit(0, "lines"))
g <- ggplotGrob(p)
g$heights[[7]] = unit(0, "lines")
grid.newpage()
grid.draw(g)

Add horizontal space between legend items

I have a legend at the bottom of a graph in ggplot2, on two lines. I need to increase the horizontal space between items.
Currently the code is:
p + theme(legend.key = element_blank(),
legend.position = "bottom",
legend.title = element_blank(),
legend.direction = "horizontal") +
guides(linetype = guide_legend(ncol = 3,keywidth=4))
But the resulting items are too close:
Any suggestion?
A bit of a hack:
#dummy data
df <- data.frame(x=1:20,
y=runif(20),
g=rep(c("a","long1","looonger1","xx"),5))
#suffix with spaces, make them same length
df$g <- substring(paste0(df$g," "),1,15)
#plot as usual
ggplot(df,aes(x,y,linetype=g)) +
geom_line() +
theme(legend.key = element_blank(),
legend.position = "bottom",
legend.title = element_blank(),
legend.direction = "horizontal") +
guides(linetype = guide_legend(ncol = 3,keywidth=4))

scatterplot with alpha transparent histograms in R

How can scatter plots with alpha transparent, scale-less histograms can be made in R, like this figure?
looks like it's not made in ggplot2.
does anyone know what command is used?
library(ggplot2)
library(gridExtra)
set.seed(42)
DF <- data.frame(x=rnorm(100,mean=c(1,5)),y=rlnorm(100,meanlog=c(8,6)),group=1:2)
p1 <- ggplot(DF,aes(x=x,y=y,colour=factor(group))) + geom_point() +
scale_x_continuous(expand=c(0.02,0)) +
scale_y_continuous(expand=c(0.02,0)) +
theme_bw() +
theme(legend.position="none",plot.margin=unit(c(0,0,0,0),"points"))
theme0 <- function(...) theme( legend.position = "none",
panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.margin = unit(0,"null"),
axis.ticks = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.ticks.length = unit(0,"null"),
axis.ticks.margin = unit(0,"null"),
panel.border=element_rect(color=NA),...)
p2 <- ggplot(DF,aes(x=x,colour=factor(group),fill=factor(group))) +
geom_density(alpha=0.5) +
scale_x_continuous(breaks=NULL,expand=c(0.02,0)) +
scale_y_continuous(breaks=NULL,expand=c(0.02,0)) +
theme_bw() +
theme0(plot.margin = unit(c(1,0,0,2.2),"lines"))
p3 <- ggplot(DF,aes(x=y,colour=factor(group),fill=factor(group))) +
geom_density(alpha=0.5) +
coord_flip() +
scale_x_continuous(labels = NULL,breaks=NULL,expand=c(0.02,0)) +
scale_y_continuous(labels = NULL,breaks=NULL,expand=c(0.02,0)) +
theme_bw() +
theme0(plot.margin = unit(c(0,1,1.2,0),"lines"))
grid.arrange(arrangeGrob(p2,ncol=2,widths=c(3,1)),
arrangeGrob(p1,p3,ncol=2,widths=c(3,1)),
heights=c(1,3))
Edit:
I couldn't find out what causes the space below the densities geoms. You can fiddle with the plot margins to avoid it, but I don't really like that.
p2 <- ggplot(DF,aes(x=x,colour=factor(group),fill=factor(group))) +
geom_density(alpha=0.5) +
scale_x_continuous(breaks=NULL,expand=c(0.02,0)) +
scale_y_continuous(breaks=NULL,expand=c(0.00,0)) +
theme_bw() +
theme0(plot.margin = unit(c(1,0,-0.48,2.2),"lines"))
p3 <- ggplot(DF,aes(x=y,colour=factor(group),fill=factor(group))) +
geom_density(alpha=0.5) +
coord_flip() +
scale_x_continuous(labels = NULL,breaks=NULL,expand=c(0.02,0)) +
scale_y_continuous(labels = NULL,breaks=NULL,expand=c(0.00,0)) +
theme_bw() +
theme0(plot.margin = unit(c(0,1,1.2,-0.48),"lines"))
I have no idea whether there is a package that does that directly, but I'm sure this can be done in R. Transparency is easy: you add another two digits to the RGB specification of a color for a given transparency:
#FF0000 # red
#FF0000FF # full opacity
#FF000000 # full transparency
Combining different plots is also easy using the layout function. As for the vertical density plot, it is just the same as the horizontal plot with x and y switched. The example given here can easily be expanded to include colors, smaller margins etc. I can try to come up with a more elaborate example if this description is not sufficient.

Resources