automatically assign width for stringr::str_wrap using base_height in cowplot::save_plot

53 views Asked by At

I want to automatically assign the width value for str_wrap so that the text fits the width of the plot, when I know the base_height I want to use in save_plot:

library(ggplot2)
library(cowplot)
library(stringr)
caption_text <- c("this is a very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very very long caption text")
p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
  geom_point() +
  theme(axis.text = element_text(size = 12, face = "bold", colour = "black"),
        axis.title = element_text(size = 16, face = "bold", colour = "black")) + 
  labs(x = "Length", y = "Width",
       caption = str_wrap(caption_text, width = 120))
p
save_plot("figures/pic.png",
          p,
          base_height = 8
          ) 

enter image description here

(text doesnt fit the width of the plot)

What I want to be able to do is automate it like so:

my_base_height = 8
str_wrap_width = my_base_height*SOME_VALUE
p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, colour = Species)) +
  geom_point() +
  theme(axis.text = element_text(size = 12, face = "bold", colour = "black"),
        axis.title = element_text(size = 16, face = "bold", colour = "black")) + 
  labs(x = "Length", y = "Width",
       caption = str_wrap(caption_text, str_wrap_width))
p
save_plot("figures/pic.png",
          p,
          base_height = my_base_height
)

but I dont know how to extract the width of a plot produced from cowplot with a known base_height value (inches) so that it can be supplied to str_wrap.

Any ideas? thanks

0

There are 0 answers