There was a suggestion on the web, but about a slightly different issue about scales = "free" in the facetting that using theme(aspect.ratio = 1) was better than coord_fixed(). That doesn’t change things for me.
Set margin units explicitly with theme(plot.margin = unit(c(-5, 5, -5, 5), "cm")), still no joy on the vertical space though it can be seen that the right and left margins are imposed correctly.
The solution is to use save the graphic to a file and then to use knitr::plot_crop() to remove the white space from the graphic and then embed the cropped file where you want it. Here’s the code:
With alternative text, i.e. !
cropped_image
Without alternative text, i.e. !
knitr insertion, JPEG
With alternative text, i.e. !
Without alternative text, i.e. !
Direct insertion
For the png file, using <img src=`r tmpPng` alt=“MyPng”>
For the png file, using <img src=`r tmpJpg` alt=“MyJpg”>
Conclusion
I got the knitr::plot_crop() solution from the answers to my stackoverflow post from stefan and axeman. Thanks to them for that. I have unpacked the details about using knitr::plot_crop() from the pointers they gave to make it easier for others hitting this to make the fix. It’s largely semantic but I disagree with them and still feel that this is a bug or very much out of the grammar of graphics style of ggplot that this is the only way to fix this. To me coord_fixed() is a modification of an “inner plot” when applied after facetting and should apply to the aspect ratio of the facets not to the containing plot. Maybe I will submit it as a request for ggplot but I’m out of energy and time for that now and will just update this file and respond to the stackoverflow post.
Text and figures are licensed under Creative Commons Attribution CC BY-SA 4.0. The figures that have been reused from other sources don't fall under this license and can be recognized by a note in their caption: "Figure from ...".
Citation
For attribution, please cite this work as
Evans (2024, July 10). Chris (Evans) R SAFAQ: Bug in facetted ggplot with coord.fixed(). Retrieved from https://www.psyctc.org/R_blog/posts/2024-07-10-bug-in-facetted-ggplot-with-coordfixed/
BibTeX citation
@misc{evans2024bug,
author = {Evans, Chris},
title = {Chris (Evans) R SAFAQ: Bug in facetted ggplot with coord.fixed()},
url = {https://www.psyctc.org/R_blog/posts/2024-07-10-bug-in-facetted-ggplot-with-coordfixed/},
year = {2024}
}