简体   繁体   English

将字体大小调整为绘图设备的大小

[英]Adjust font size to size of plot device

Often I am in a position when I have to adjust the size of the output image.当我必须调整输出图像的大小时,我经常处于一个位置。 Unfortunately, it means that usually I have to adjust font size, to make things readable.不幸的是,这意味着通常我必须调整字体大小,以使内容可读。

For example, if the following plot例如,如果下面的情节

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))

is saved to 12'' x 6'' image things look pretty good:保存到 12'' x 6'' 图像看起来不错:

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

12'' x 6'' output 12'' x 6'' 输出

在此处输入图片说明

however if I increase dimensions to 36'' x 18'' the fonts are unreadble:但是,如果我将尺寸增加到 36'' x 18'',字体将无法阅读:

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

36'' x 18'' 36 英寸 x 18 英寸

在此处输入图片说明

Is there any general strategy which allows us to change output resolution without constant tinkering with the font sizes?是否有任何通用策略可以让我们更改输出分辨率而无需不断修改字体大小?

You need to define the size of your text items as well as the plotting environment.您需要定义文本项的大小以及绘图环境。

Since you want to dynamically scale it will likely be easiest to scale your fonts and save sizes to the same values.由于您想要动态缩放,因此缩放字体并将大小保存为相同的值可能是最简单的。 See ggplot2 - The unit of size for the divide by 2.834646 value to correct for font sizes.请参阅ggplot2 -除以 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM