Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjusting the "margin" space for axis text in ggplot2

Which property, if any, in ggplot controls
the width (or amount of blank space) of the axis text?


In the example below, my ultimate goal is to "push in" the left-hand side of the top graph so that it lines up with the bottom graph.

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

As a last resort, I realize I could modify the axis text itself, but then I would also need to calculate the cuts for each graph.

enter image description here

Reproducible 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"))
like image 766
Ricardo Saporta Avatar asked Mar 10 '14 02:03

Ricardo Saporta


People also ask

How do I change the margins in ggplot2?

Increase margins In order to modify the plot margins set the margin function inside the plot. margin component of the theme function. The margins are measured with points ( "pt" ), but you can use other unit measure in the unit argument, like centimeters.

How do I make my axis labels bigger in ggplot2?

To increase the X-axis labels font size using ggplot2, we can use axis. text. x argument of theme function where we can define the text size for axis element.

How do I change the Y axis scale in ggplot2?

Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.

How do I change the axis title size?

You can change axis text and label size with arguments axis. text= and axis. title= in function theme() . If you need, for example, change only x axis title size, then use axis.


1 Answers

Here is one solution.

The idea was borrowed from "Having horizontal instead of vertical labels on 2x1 facets and splitting y-label Define a function

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)

Here is the output.

enter image description here

like image 157
Jd Baba Avatar answered Oct 05 '22 01:10

Jd Baba