3
votes

I'm plotting hundreds of plots through a loop. Each plot has different parameters, which leads to y-axis labels ranging from, say, 0.1-0.9 in some plots to 100-1000 in others. Right now, when they're plotted, the total size of the plot is held constant, which means that the location of the y-axis is shifted to the right when the y-axis labels are long, or to the left, when the labels are short.

I want to fix the panel width across all plots. Essentially, there would be white space to the left of the y-axis title if the labels are short.

My question is somewhat similar to this, but I don't have enough knowledge of gtable to modify the solution for what I want. How achieve identical facet sizes and scales in several multi-facet ggplot2 graphics?

Toy example:

df <- data.frame(x = c(rnorm(10, 0.1, 0.1), rnorm(10, 1000, 100)), 
y = c(rnorm(10, 0.1, 0.1), rnorm(10, 10000, 100)), 
name = c(rep(1, 10), rep(2, 10)))

for(i in 1:2){

p <- ggplot(df[df$name == i,]) +
    geom_point(aes(x = x, y = y))

filename <- paste("fig", i, ".jpg", sep = "")
jpeg(filename, width = 6.5, height = 5.5, units = "in", pointsize = 12, quality = 100, res = 500)
print(p)
dev.off()
    }
1

1 Answers

3
votes

You could produce a dummy plot, 'p', with the full dataset, convert it to a gtable with 'g=ggplotGrob(p)', store its widths 'w=g$widths', and for each plot in the loop replace the gtable's widths by 'w'.

p <- ggplot(df) +
  geom_point(aes(x = x, y = y))
g <- ggplotGrob(p)
w <- g$widths

pdf("test.pdf")
for(i in 1:2){

  p <- ggplot(df[df$name == i,]) +
    geom_point(aes(x = x, y = y))
  g <- ggplotGrob(p)
  g$widths <- w
  grid::grid.newpage()
  grid::grid.draw(g)
}
dev.off()

enter image description here