Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying ggplot2 panel width

Tags:

r

ggplot2

r-grid

I have two ggplots on the same page, and I'd like their panels to be the same width.

Some sample data:

dfr1 <- data.frame(
  time = 1:10,
  value = runif(10)  
)

dfr2 <- data.frame(
  time = 1:10,
  value = runif(10, 1000, 1001)  
)

One plot below the other:

p1 <- ggplot(dfr1, aes(time, value)) + geom_line()
p2 <- ggplot(dfr2, aes(time, value)) + geom_line()

grid.newpage()
pushViewport(viewport(layout = grid.layout(2, 1)))   
print(p1, vp = viewport(layout.pos.row = 1, layout.pos.col = 1))         
print(p2, vp = viewport(layout.pos.row = 2, layout.pos.col = 1))

How do I specify the panel widths and positions in each plot, in order to make them line up?

(I don't want to combine the plots with faceting; it isn't appropriate in my real-world example.)

like image 500
Richie Cotton Avatar asked Mar 30 '11 16:03

Richie Cotton


People also ask

How do I change the width of a ggplot2?

To increase the width of axes (both X-axis and Y-axis at the same time) using ggplot2 in R, we can use theme function with axis. line argument where we can set element_line argument to a larger value.

What is %>% in ggplot?

%>% is a pipe operator reexported from the magrittr package. Start by reading the vignette. Introducing magrittr. Adding things to a ggplot changes the object that gets created. The print method of ggplot draws an appropriate plot depending upon the contents of the variable.

How do I use Ggsave?

In most cases ggsave() is the simplest way to save your plot, but sometimes you may wish to save the plot by writing directly to a graphics device. To do this, you can open a regular R graphics device such as png() or pdf() , print the plot, and then close the device using dev. off() .


1 Answers

Original solution:

 #   install.packages("ggExtra", repos="http://R-Forge.R-project.org")
 #   library(ggExtra)
 #   align.plots(p1, p2)

Edit (22/03/13):

Since ggExtra doesn't exist anymore (and many internals of ggplot2 have changed), it's better to use the merging functions (rbind, cbind) provided by the gtable package,

gl = lapply(list(p1,p2), ggplotGrob)     
library(gtable)
g = do.call(rbind, c(gl, size="first"))
g$widths = do.call(unit.pmax, lapply(gl, "[[", "widths"))

grid.newpage()
grid.draw(g)    

enter image description here

like image 63
Andrie Avatar answered Sep 25 '22 04:09

Andrie