Hi there - I am trying to make a typical figure for a grant, in which we usually have a nice plot with a bounding box, and an adjacent chatty figure legend (usually below) with its own matching bounding box.
An example is shown here
Another example with a ggplot is shown here
Note the mismatch between the tag (upper left) and the figure_legend (5B vs 4B) .
Ideally, I would like to do this programmatically and prevent these kinds of errors.
I have tried a few options, with only modest success.
The plot with a bounding box is pretty straightforward, with
theme(plot.background = element_rect(color='black'))
I would like an easy way to create a auto-wrapping textGrob within a bounding box, with better control of the spacing between lines (lineheight?). There are probably better approaches.
I would also like a better way to put these together, so that the bottom of the plot bounding box overlays the top of the figure_legend bounding box.
Here are things that I have tried in a reprex.
# Goal: plot in box with figure_legend in box below
library(tidyverse)
library(gridExtra)
#>
#> Attaching package: 'gridExtra'
#> The following object is masked from 'package:dplyr':
#>
#> combine
library(grid)
p <- iris %>%
ggplot() +
aes(x= Sepal.Width, y = Sepal.Length) +
geom_point()
p2 <- p +
theme(plot.background = element_rect(color='black'))
legend <- "Figure 1. An Amazing Plot. This is a totally awesome plot. It has great properties. The \n
points are black. The background is gray. You should definitely fund this grant."
# one option - caption
p2 +
labs(caption = legend) +
theme(plot.caption = element_text(size = 12, hjust = 0,
margin = margin(15,0,0,0)))
# notes - pretty good, but no dividing line between the plot and the legend
# also need lower lineheight/space between lines
# another option - textGrob
figlegend <- textGrob(legend,
x = 0.01,
just = 'left',
gp = gpar(fontsize=12) +
theme(plot.background = element_rect(color='black')))
c <- textGrob(legend, just = 'left', x = 0.01,
gp=gpar(fontsize = 11))
b <- arrangeGrob (p2, c,
nrow = 2,
heights = unit(c(3, 0.25),
c('null', 'null')))
grid.newpage()
grid.rect(x=0, y=0, width = 2, height = 0.15,
gp=gpar(fill = NULL))
grid.draw(b)
# notes - also good, but would like to have
# plot box and figure_legend box align
# bottom of plot box and top of figure_legend box on top of each other
# also still need lower lineheight/space between lines
#PLOTRIX option - not much success
library(plotrix)
Created on 2020-02-06 by the reprex package (v0.3.0)