Left Align Two Graph Edges (Ggplot)

Left align two graph edges (ggplot)

Try this,

 gA <- ggplotGrob(A)
gB <- ggplotGrob(B)
maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
gA$widths[2:5] <- as.list(maxWidth)
gB$widths[2:5] <- as.list(maxWidth)
grid.arrange(gA, gB, ncol=1)

Edit

Here's a more general solution (works with any number of plots) using a modified version of rbind.gtable included in gridExtra

gA <- ggplotGrob(A)
gB <- ggplotGrob(B)
grid::grid.newpage()
grid::grid.draw(rbind(gA, gB))

Align multiple ggplot2 plots with grid

If you don't mind a shameless kludge, just add an extra character to the longest label in p1, like this:

p1 <- ggplot(data1) +
aes(x=x, y=y, colour=x) +
geom_line() +
scale_y_continuous(breaks = seq(200, 1000, 200),
labels = c(seq(200, 800, 200), " 1000"))

I have two underlying questions, which I hope you'll forgive if you have your reasons:

1) Why not use the same y axis on both? I feel like that's a more straight-forward approach, and easily achieved in your above example by adding scale_y_continuous(limits = c(0, 10000)) to p1.

2) Is the functionality provided by facet_wrap not adequate here? It's hard to know what your data structure is actually like, but here's a toy example of how I'd do this:

library(ggplot2)

# Maybe your dataset is like this
x <- data.frame(x = c(1, 2),
y1 = c(0, 1000),
y2 = c(0, 10000))

# Molten data makes a lot of things easier in ggplot
x.melt <- melt(x, id.var = "x", measure.var = c("y1", "y2"))

# Plot it - one page, two facets, identical axes (though you could change them),
# one legend
ggplot(x.melt, aes(x = x, y = value, color = x)) +
geom_line() +
facet_wrap( ~ variable, nrow = 2)

How to align two plots with ggplot?

I'd suggest the following,

library(gtable)
a <- ggplotGrob(p)
b <- ggplotGrob(p.eff)
grid.newpage()
grid.draw(gtable:::cbind_gtable(a, b, "first"))

but if you leave the default theme and margins of both plots, you'll notice that the alignment is still problematic, simply because the y values are not identical in both plot panels.

can not left align with cowplot package

The problem is that the raster object is placed bang in the middle of your plot. Check ggplot() + annotation_custom(rasterGrob(ft_raster)) without theme_void. You can play around with the coordinates for your raster (by the way, the Infs are defaults...

library(flextable)
library(grid)
library(cowplot)
library(tidyverse)

mydf <- tibble(a = c(1,2,3,4,5,4),
b = c(4,4,4,3,3,3))

p1 <- mydf %>% ggplot(aes(x = a, y = b, color = as.factor(b))) + geom_point()

ft_raster <- mydf %>%
flextable::flextable() %>%
as_raster()

p2 <-
ggplot() +
theme_void() +
# play around with this !
annotation_custom(rasterGrob(ft_raster), xmax = 0.2)

cowplot::plot_grid(p1, p2, nrow = 2, ncol = 1, rel_heights = c(1, 1) )

Sample Image

Created on 2022-06-08 by the reprex package (v2.0.1)



Related Topics



Leave a reply



Submit