R Notebook中ggarrange共用图例出现多余空白绘图的解决问询
ggarrange + common.legend = TRUE in R Notebooks Hey there! I’ve run into this exact annoying problem with ggarrange in R Notebooks before—that random blank plot popping up when you enable a shared legend is such a buzzkill. Let’s break down why this happens and fix it for good.
What’s Causing the Blank Plot?
When you set common.legend = TRUE, ggarrange extracts the legend from your plots and tries to embed it into the layout. In R Notebook’s HTML rendering environment, this sometimes leaves behind a hidden temporary plot that ends up showing as blank. Plus, without a shared legend, the inconsistent plot sizes happen because one plot has extra space allocated for its legend while the other doesn’t.
Solution 1: Manually Extract and Add the Shared Legend
This method avoids the common.legend parameter entirely by building the layout yourself, which eliminates the blank plot and ensures uniform plot sizes. Here’s how to adjust your code:
# Load required packages (if not already loaded) library(ggpubr) library(gridExtra) # Create your first histogram WITHOUT a legend p1 <- gghistogram(data, title="MOTIVATION SCORES", x="MOTIVATION", y="..density..", add_density=TRUE, add = "median", rug = TRUE, bins=15, color="#69c8ECFF", fill="#69c8ECFF", legend = "none") # Disable legend here # Create your second histogram (keep the legend temporarily) p2 <- gghistogram(data, title="MOTIVATION BY AGE GROUP", x = "MOTIVATION", y="..density..", add_density=TRUE, add = "median", rug = TRUE, bins=15, color = "AGE_GROUP", fill = "AGE_GROUP", palette = c("#69c8ECFF", "#E762D7FF")) # Extract the shared legend from p2 shared_legend <- get_legend(p2) # Arrange the two plots (remove p2's legend now) plot_grid <- ggarrange(p1, p2 + theme(legend.position = "none"), ncol = 2, # Force side-by-side layout align = "h") # Align plots horizontally for uniform size # Add the shared legend to the bottom of the plot grid annotate_figure(plot_grid, bottom = shared_legend)
Solution 2: Use grid.arrange for More Control
If you prefer using gridExtra instead of ggpubr’s annotation tools, this works just as well:
library(gridExtra) # Reuse p1, p2, and shared_legend from Solution 1 grid.arrange(p1, p2 + theme(legend.position = "none"), ncol = 2, bottom = shared_legend)
Why This Works
By manually extracting the legend and adding it after arranging the plots, we avoid the hidden temporary plot that common.legend = TRUE creates in R Notebooks. We also ensure both main plots have identical dimensions (since neither has a legend taking up space), then add the shared legend below them cleanly.
内容的提问来源于stack exchange,提问作者BKV

