0

I want to combine these two graphs :

p1 <- ggplot(iris, aes(Sepal.Length)) + 
  geom_density() + 
  facet_wrap(~ Species)

p2 <- ggplot(iris, aes(Sepal.Length)) + 
  geom_density()

To combine, I do :

multiplot(p1, p2, cols = 2)

But it is not the desired shape.

I would like the graph p2 has the same dimensions than others and is situated just next to the last faceted graph.

Thanks for help

Loulou
  • 703
  • 5
  • 17
  • `facet_grid(~ Species, margins = TRUE)` will work here. But for the general case, this is not easy to do. The `cowplot` package does alignments, but you can't align facetted and non-facetted plots. – Axeman Mar 29 '17 at 10:14

2 Answers2

0

Not sure if this is applicable in you generic case, but with facet_grid instead of facet_wrap, you can use the margins argument:

library(ggplot2)

ggplot(iris, aes(Sepal.Length)) + 
    geom_density() + 
    facet_grid(. ~ Species, margins = T)

If you question is more generic the answer probably lies in grid.arrange.
Something like this could be a start:

library(gridExtra)

grid.arrange(arrangeGrob(p1, p2, 
                         widths = c(3,1), 
                         heights = c(1,20), 
                         layout_matrix = matrix(c(1,1,NA,2),2)))

As you can see there are several problems (different axes, top strip), but working with grid could gets complicated quickly.

GGamba
  • 13,140
  • 3
  • 38
  • 47
0

This code should work:

p1 <- ggplot(iris, aes(Sepal.Length)) + 
      geom_density() + 
      ylim(limits = c(0, 1.25))+
      facet_wrap(~ Species)

p2 <- ggplot(iris, aes(Sepal.Length)) + 
      geom_density() +
      ggtitle("") + # ad empty title as place holder
      labs(y = "", x = "") + # hide axis labels
      ylim(limits = c(0, 1.25)) + # y axis values should be fixed in both plots
      coord_fixed(ratio=20/1) + # ratio of x- and y-axis to reduce width of plot
      theme(axis.ticks.y = element_blank(), axis.text.y = element_blank(), axis.line.y = element_blank(),
      plot.margin=unit(c(0,0,0.65,-10), "lines")) # margin between plots = "0.65"

I fiddled a bit and used just different styling options to produce this result. If you have more plots than this one I would recommend to use one theme for all.

You can use either the multiplot function that you are already using

multiplot(p1, p2, cols = 2)

or you install the packages gridExtra and grid and use that one:

grid.arrange(p1, p2, ncol=2) 

Hope this helps!

Elena
  • 121
  • 8