在 cowplot::save_plot 中使用 base_height 自动为 stringr::str_wrap 分配宽度

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

提问人:user63230 提问时间:10/27/2023 更新时间:10/27/2023 访问量:34

问:

我想自动分配值,以便文本适合绘图的宽度,当我知道我想在以下方面使用时:widthstr_wrapbase_heightsave_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

(文字与剧情宽度不符)

我希望能够做的是像这样自动化它:

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
)

但我不知道如何提取具有已知值(英寸)的绘图的宽度,以便将其提供给.cowplotbase_heightstr_wrap

有什么想法吗? 谢谢

r ggplot2 纵梁 牛图

评论

0赞 margusl 10/27/2023
这对你有用吗 - stackoverflow.com/a/65444374/646761
0赞 user63230 10/27/2023
不幸的是,它没有回答我的问题,也不是自动化的。谢谢
1赞 Andrew Gustar 10/27/2023
您可以尝试 - 您可能需要根据默认尺寸将 2 调整得更高或更低。str_wrap_width = my_base_height * (2 * dev.size()[1])
1赞 user63230 11/2/2023
@AndrewGustar谢谢!这似乎有效,但我花了一段时间才获得一致的输出。我玩了一圈,直到我让它工作,但是当我将其应用于我的真实数据时,它不起作用 - 事实证明,我正在添加自然地改变字体大小,扭曲了情节。我还意识到,如果你正在绘制不同类型的图形,你需要计算出一个单独的值(从 ) (例如,但好消息是,该值似乎适用于所有图,而不管 和 的数量如何。干杯2theme_cowplot()2facet_wrap)facet_wraprowscols

答: 暂无答案