【问题标题】:Adjust font size to size of plot device将字体大小调整为绘图设备的大小
【发布时间】:2019-02-17 14:58:47
【问题描述】:

我经常需要调整输出图像的大小。不幸的是,这意味着通常我必须调整字体大小以使内容可读。

例如,如果下面的情节

library(ggplot2)
library(tibble)
library(stringi)

set.seed(1)

df <- tibble(
  x = stri_rand_strings(10, 20), 
  y = runif(10) * 10, 
  label = stri_rand_strings(10, 10)
)


p <- ggplot(df, aes(x, y)) +
  geom_text(aes(label = label)) +
  scale_x_discrete(position = "top") +
  theme(axis.text.x = element_text(angle = 90, hjust = 0))

保存到 12'' x 6'' 的图像看起来还不错:

p + ggsave("test_small.png", width = 12, height = 6, unit = "in")

12'' x 6'' output

但是,如果我将尺寸增加到 36'' x 18'',字体将无法阅读:

p + ggsave("test_large.png", width = 36, height = 18, unit = "in")

36'' x 18''

是否有任何通用策略允许我们更改输出分辨率而无需不断修改字体大小?

【问题讨论】:

  • 是否试图保持与页面大小相同的文本大小比例?当您查看页面的“真实”大小时,它们是可读的,因为它们都使用pt 10 字体(我认为这是默认值)。一种方法是预先定义一个比率,但我不相信ggplot 会相对于输出大小缩放字体。
  • 我会说,ggsave() 的使用方式非常奇怪。您也应该在 ggplot 中设置文本大小,例如+ theme_bw(base_size = 16).
  • @Anonymouscoward 这正是我想要的。
  • 答案在[这里] (christophenicault.com/post/understand_size_dimension_ggplot2)。您只需添加 showtext_opts(dpi = 300) 然后创建并保存您的绘图。

标签: r ggplot2 fonts resolution


【解决方案1】:

您需要定义文本项的大小以及绘图环境。

由于您想要动态缩放,因此缩放字体并将大小保存为相同的值可能是最简单的。请参阅 ggplot2 - The unit of size 以获取除以 2.834646 的值以更正字体大小。

base = 6 # set the height of your figure (and font)
expand = 2 # font size increase (arbitrarily set at 2 for the moment)

 ggplot(df, aes(x, y)) +
   geom_text(aes(label = label), size = base * expand / 2.834646) +
   scale_x_discrete(position = "top") +
    theme(axis.text.x = element_text(angle = 90, hjust = 0, size = base * expand ),
     axis.text.y = element_text(size = base * expand )) 

ggsave("test_large.png", width = base * 2, height = base, unit = "in", dpi = 300) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2014-11-30
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    相关资源
    最近更新 更多