Setting margin field for axis text in ggplot2

What property, if any, in the ggplotcontrol is the width (or number of spaces) of the axis text?


In the example below, my final goal is to “insert” the left side of the upper graph so that it aligns with the lower graph.

I tried theme(plot.margin=..), but it affects the edge of the entire plot.
facet'ing doesn't help either, since the scales on y are different.

As a last resort, I understand that I can change the text of the axis itself, but then I will also need to calculate the cuts for each graph.

enter image description here

Playable example:

library(ggplot2)
library(scales)

D <- data.frame(x=LETTERS[1:5],  y1=1:5, y2=1:5 * 10^6)

P.base <- ggplot(data=D, aes(x=x)) + 
            scale_y_continuous(labels=comma)

Plots <- list(
    short = P.base + geom_bar(aes(y=y1), stat="identity", width=.5)
  , long  = P.base + geom_bar(aes(y=y2), stat="identity", width=.5) 
  )

do.call(grid.arrange, c(Plots, ncol=1, main="Sample Plots"))
+4
source share
1 answer

Here is one solution.

, 2x1 y-

align_plots1 <- function (...) {
    pl <- list(...)
    stopifnot(do.call(all, lapply(pl, inherits, "gg")))
    gl <- lapply(pl, ggplotGrob)
    bind2 <- function(x, y) gtable:::rbind_gtable(x, y, "first")
    combined <- Reduce(bind2, gl[-1], gl[[1]])
    wl <- lapply(gl, "[[", "widths")
    combined$widths <- do.call(grid::unit.pmax, wl)
    grid::grid.newpage()
    grid::grid.draw(combined)
}

short <- P.base + geom_bar(aes(y=y1), stat="identity", width=.5)
long <- P.base + geom_bar(aes(y=y2), stat="identity", width=.5) 

#Now, align the plots
align_plots1(short, long)

.

enter image description here

+7

Source: https://habr.com/ru/post/1530899/


All Articles