wilkelab / cowplot

cowplot: Streamlined Plot Theme and Plot Annotations for ggplot2
https://wilkelab.org/cowplot/
704 stars 84 forks source link

insert_xaxis_grob with facet_grid, more than one marginal plot on x-axis #151

Open ccshao opened 4 years ago

ccshao commented 4 years ago

I would like to add the marginal plots to a gglot2 object, so the axis match. However, I could not manage it with the insert_xaxis_grob and axis_canvas.

A very simple example

The major plot:

p01 <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) +
  geom_point() +
  theme_cowplot()

The margin, with facet_grid

p05 <- axis_canvas(p01, axis = "x") +
  geom_histogram(data = iris, aes(Sepal.Length), alpha = 0.8) +
  scale_color_manual(values = RColorBrewer::brewer.pal(4, "Set2")) +
  scale_fill_manual(values = RColorBrewer::brewer.pal(4, "Set2")) +
  facet_grid(vars(Species))

Screenshot from 2019-12-03 09-39-11

combined_plot <- insert_xaxis_grob(p01, p05, position = "bottom") it gives the warning:

stat_bin()usingbins = 30. Pick better value withbinwidth. Warning messages: 1: Removed 6 rows containing missing values (geom_bar). 2: In get_panel(grob) : Multiple panels found; returning the first one. Select a panel withpanelor return all withreturn_all = TRUE`.

and indeed only the first one is used.

Screenshot from 2019-12-03 09-38-51

Any suggestions to add more than one marginal plots on the axis, as I would like to compare the distribution between different groups.

Thanks very much.

zhuoxinChen-code commented 1 year ago

try this: library(patchwork) combined_plot <- insert_xaxis_grob(p01, wrap_plots(p05), position = "bottom") #wrap_plots would combine them as one ggdraw(combined_plot)