I'm using cowplot package to create a plot grid. My problem comes when I want to plot vertically two plots with different widths. Here is an example:
library(dplyr)
library(ggplot2)
library(cowplot)
plot1 = iris %>%
ggplot(aes(x = Species, y = Sepal.Width, fill = Species)) +
geom_col()
plot2 = iris %>%
filter(Species != 'virginica') %>%
ggplot(aes(x = Species, y = Sepal.Width, fill = Species)) +
geom_col()
w1 = max(layer_data(plot1, 1)$x)
w2 = max(layer_data(plot2, 1)$x)
plot_grid(plot1, plot2, align = 'v', ncol = 1, rel_widths = c(w1, w2), axis = 'l')
As you can see in the code, I use layer_data() function to extract how many columns I have in the plot, because I want to run it recursively, and sometimes, some groups are dropped, so I ensure the number of columns. So the goal would be to align the columns vertically from different plots. In the previous code, rel_width argument has no effect.
I've tried somethings like this:
plot_grid(plot1,
plot_grid(plot2, NA, align = 'h', ncol = 2, rel_widths = c(w2, w1-w2)),
align = 'v', ncol = 1, axis = 'lr')
But it's not working as expected and depends that w1 > w2. Some help would be appreciated
Edited:
Because maybe, the previous code was a little bit confusing, I add a new one, which create two different dataframes to plot. The goal would be to align x-axis from both plots. Legend alignment would not be needed, only the x-axis.
library(ggplot2)
library(cowplot)
d1 = data.frame(length = c('large', 'medium', 'small'),
meters = c(100, 50, 30))
d2 = data.frame(speed = c('high', 'slow'),
value =c(200, 45))
p1 = ggplot(d1, aes(x = length, y = meters, fill = length)) +
geom_col() +
scale_fill_viridis_d()
p2 = ggplot(d2, aes(x = speed, y = value, fill = speed)) +
geom_col()
p_ls = list(p1, p2)
n_x = sapply(p_ls, function(p) {
max(layer_data(p, 1)$x)
})
plot_grid(plotlist = p_ls, align = 'v', ncol = 1, rel_widths = n_x)