Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggarrange with common legend produces extra blank plot in markdown

I am using R Notebooks and have a chunk with some code for arranged histograms. When I use a common legend it produces an extra empty plot, which looks terrible in the rendered html file. This phenomenon disappears without a shared legend, but the plot looks terrible since they are not of the same size. Is there any way to stop it from producing an extra empty graph?

Notebook chunk output

and the code being used in the chunk

 ```{r}

ggarrange(

gghistogram(data, title="MOTIVATION SCORES", x="MOTIVATION", y="..density..", 
add_density=TRUE, add = "median", rug = TRUE, bins=15, color="#69c8ECFF", 
fill="#69c8ECFF") , 


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")
          )

, legend = "bottom" 
, common.legend = TRUE

)
```
like image 564
BKV Avatar asked Nov 07 '22 12:11

BKV


1 Answers

Edit: If you run the 2nd block below as a block of code in an rmarkdown document, it still generates the extra blank plot. If you run each line of the 2nd block manually (i.e. one at a time) it generates just the single desired plot. I think this still counts as a solution though because even running the first code block one at a time results in the extra blank plot.

This seems to reproduce the problem when run in an rnotebook:

p1 = ggplot(mtcars, aes(x = mpg, y = cyl)) +
    geom_point()
p2 = ggplot(mtcars, aes(x = drat, y = vs)) +
    geom_point()
ggarrange(p1, p2, ncol = 2, nrow = 1, common.legend = TRUE, legend = "bottom", labels = c("A", "B", "C"))

If instead I assigned the ggarrange object to p, then the problem goes away:

p1 = ggplot(mtcars, aes(x = mpg, y = cyl)) +
    geom_point()
p2 = ggplot(mtcars, aes(x = drat, y = vs)) +
    geom_point()
p = ggarrange(p1, p2, ncol = 2, nrow = 1, common.legend = TRUE, legend = "bottom", labels = c("A", "B", "C"))
p

No idea why. Highly unsatisfactory for me, but it seems to work.

like image 160
buggaby Avatar answered Nov 14 '22 22:11

buggaby