Is there a way to align a table in a Grob to the left side of the panel instead of having it centred?
In the example bellow you can see that the table is in the centre of the lower panel, but I would like it to be aligned to the left side. I could not find any way of doing this.
library(gridExtra)
library(grid)
grid.arrange(
grobTree(
rectGrob(gp=gpar(fill="gray", col = NA)),
textGrob("Title\nThis is some text.\nAnd more text.\nAnd more text.",
x = 0.01, y=0.95, gp = gpar(fontsize = 12), just = c("left", "top"))
),
grobTree(
rectGrob(gp=gpar(fill="lightgray", col = NA)),
tableGrob(head(mtcars[1:4]), rows = NULL)
)
)
Created on 2023-10-19 with reprex v2.0.2
I am new to Grobs so if you have any general suggestions how to achieve this in a better way please let me know!
You would need to give the tableGrob
its own viewport to be drawn into:
library(gridExtra)
library(grid)
grid.arrange(
grobTree(
rectGrob(gp=gpar(fill="gray", col = NA)),
textGrob("Title\nThis is some text.\nAnd more text.\nAnd more text.",
x = 0.01, y=0.95, gp = gpar(fontsize = 12), just = c("left", "top"))
),
grobTree(
rectGrob(gp=gpar(fill="lightgray", col = NA)),
tableGrob(head(mtcars[1:4]), rows = NULL,
vp = viewport(x = 0.18, y = 0.5))
)
)
One of the difficulties here is that a tableGrob
is a fixed width, but your plotting device isn't. This means that selecting an x value for the viewport requires adjustment depending on the plot size. If you want to have the table remain stuck on the left side however your plot is scaled, you can use the width of a copy of the grob itself to dictate x position:
grid.arrange(
grobTree(
rectGrob(gp=gpar(fill="gray", col = NA)),
textGrob("Title\nThis is some text.\nAnd more text.\nAnd more text.",
x = 0.01, y=0.95, gp = gpar(fontsize = 12), just = c("left", "top"))
),
grobTree(
rectGrob(gp=gpar(fill="lightgray", col = NA)),
tableGrob(head(mtcars[1:4]), rows = NULL,
vp = viewport(x = unit(1.5, 'grobwidth',
data = tableGrob(head(mtcars[1:4]),
rows = NULL)),
y = 0.5))
)
Now however the plot is scaled, the table remains exactly aligned to the left.