11

Following a previous R post Specifying ggplot2 panel width, I have been able to produce this plot:

enter image description here

with this code.

You can find the output of dput(datos) at http://ubuntuone.com/0Nlb97mOeDhSbFrbFKCeEG

Now my question is how can I remove/reduce the white space between the graphs. I have found examples with ggExtra package, ggplot and facet, multiplots with options as plot.margin or panel.margin but couldn't find how to apply to my case.

Thanks for your help.

EDIT: I have just noticed that plots have not the same width. It is needed they have the same width so they can share x axis labels from bottom plot.

Community
  • 1
  • 1
pacomet
  • 5,011
  • 12
  • 59
  • 111

2 Answers2

7

Using xlab(NULL) instead of xlab(" ") will remove some space off the bottom of each plot.

Using opts(plot.margin = unit(c(0,0,0,0), "cm")) will remove a little space from the edges.


I think that your have overcomplicated things by creating 5 separate graphs and recombining them. Faceting is much easier.

mdatos <- melt(datos[, -1], id.vars = "dia")
(p_all <- ggplot(mdatos, aes(dia, value)) +
  geom_line(colour = "blue") +
  facet_grid(variable ~ ., scale = "free_y") +
  xlab("Day") +
  ylab(NULL) 
)

The plot panels aren't the same width because some y axis labels have three digit numbers, and some only two. Either change the formatting of the y axis, or use my facetting suggestion.

Richie Cotton
  • 118,240
  • 47
  • 247
  • 360
  • Hi Richie, I have tried your suggestion and have not noticed significant change in the plot – pacomet Oct 26 '11 at 12:52
  • @pacomet: The difference is subtle. Turn on plot history (in the RGui plot window History -> Recording) and Page Up/Down to compare. Or use facetting, which will give you minimal spaces. – Richie Cotton Oct 26 '11 at 13:08
  • As a newbie maybe I have overcomplicated. I had created separated graphs for another purpose and then decided to try combining. I had tried facetting before as you suggest from a previous post and have another question. Here, `ggplot` uses geom_line for all 5 graphs but I want the one at the bottom uses geom_bar(). Is it possible in this case? Thanks again. – pacomet Oct 26 '11 at 13:27
  • @pacomet: Different geoms in different facets is a big enough problem that it deserves it's own question. – Richie Cotton Oct 26 '11 at 14:07
  • @pacomet: See http://stackoverflow.com/questions/7903972/can-you-specify-different-geoms-for-different-facets-in-a-ggplot/7904058 – Richie Cotton Oct 26 '11 at 14:22
2

You can layout and control the margins of several subplots with par and layout. For example:

  par (fig=c(0,1,0,1), # Figure region in the device display region (x1,x2,y1,y2)
       omi=c(0,0,0.3,0), # global margins in inches (bottom, left, top, right)
       mai=c(0.1,0.1,0.3,0.1)) # subplot margins in inches (bottom, left, top, right)
  layout(matrix(1:4, 2, 2, byrow = TRUE))
Itamar
  • 2,111
  • 13
  • 16