调整字体大小以适应绘图设备的大小。

9

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

例如,如果以下图表

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英寸输出

在此输入图片描述

但是,如果我将尺寸增加到36英寸 x 18英寸,则字体将变得不可读:

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

36'' x 18''

enter image description here

有没有一般的策略可以在不经常调整字体大小的情况下更改输出分辨率?


你是否试图保持文本大小与页面大小的比例相同?当您查看页面的“真实”大小时,它们是可读的,因为它们都使用 pt 10 字体(我认为这是默认值)。一种方法是事先定义一个比率,但我不认为 ggplot 会根据输出大小缩放字体。 - Anonymous coward
https://dev59.com/FVcP5IYBdhLWcg3wN3qP - Tung
我觉得使用 ggsave() 的方式非常奇怪。你应该在 ggplot 中设置文本大小,例如 + theme_bw(base_size = 16) - Tung
@Anonymouscoward 这正是我正在寻找的。 - user10355350
答案在这里。你只需要添加showtext_opts(dpi = 300),然后创建并保存你的图表即可。 - Abdurrahman Yavuz
1个回答

6
你需要定义文本项的大小以及绘图环境。
由于你想要动态缩放,最好将字体缩放并保存到相同的值。请参见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) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接