thomasp85 / patchwork

The Composer of ggplots
https://patchwork.data-imaginist.com
Other
2.42k stars 157 forks source link

Add a plot to an existing patchwork object #353

Open laresbernardo opened 4 months ago

laresbernardo commented 4 months ago

Hi Thomas and community. I've been using patchwork for years now and it's amazingly useful and easy to use. But today I'd like to ask how can I add a ggplot2 object to an already existing patchwork object. The original patchwork object comes from a function that returns a plot with 8 plots in 4 rows and 2 columns. It contains a title, captions, and an overall theme added over it. But now I'd like to add a new wide plot under 1 and 2, over 3 and 4. It's easy to achieve from scratch, but given I have an object that another library provides and has been already patched together, how can I do this? Thanks a lot for all your contributions to the R community!

thomasp85 commented 4 months ago

To understand correctly, you wan't your plot to be added into the returned patchwork so that it inherits the theme, caption etc?

laresbernardo commented 4 months ago

Hi @thomasp85 thanks for the follow-up.

Sharing a visual example. The first plot is a returned patchwork and the second one is what I'd like to achieve: adding/appending a new ggplot2 object to an existing patchwork with a customized grid.

Screenshot 2024-03-05 093510

thomasp85 commented 4 months ago

I'm afraid there is really no "non-hacky" way of doing this. You could add your plot with + and then use a custom design to make it work, but if the return value are already using a design then that would be overwritten

try something like:

p <- fun_returning_patchwork()
my_plot <- fun_creating_my_plot()
p + my_plot + plot_layout(design = c("
AB
GG
CD
EF
"))

and see if it works as expected

laresbernardo commented 4 months ago

That was a great hint Thomas, but wasn't exactly what I was expecting. So running your example, I was getting something like AB CD EF GH II

But that's because each of the previous plots was already a patchwork object! So, setting ... + plot_layout(design = c("\nA\nE\nB\nC\nD\n")) did the trick!

Additional tests: I tried setting up nrow and ncol but I guess that when design is being used, those are simply ignored. Do you want me to add this behaviour to design's parameter in a PR?