将字体大小调整为绘图设备的大小 [英] Adjust font size to size of plot device

查看:68
本文介绍了将字体大小调整为绘图设备的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

例如,如果以下情节

 库(ggplot2)图书馆(小标题)库(字符串)set.seed(1)df<-tibble(x = stri_rand_strings(10,20),y = runif(10)* 10,标签= stri_rand_strings(10,10))p<-ggplot(df,aes(x,y))+geom_text(aes(label = label))+scale_x_discrete(position ="top")+主题(axis.text.x = element_text(角度= 90,高度= 0)) 

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

  p + ggsave("test_small.png",宽度= 12,高度= 6,单位="in") 

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

  p + ggsave("test_large.png",宽度= 36,高度= 18,单位="in") 

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

解决方案

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

由于要动态缩放,可能最容易缩放字体并将大小保存为相同的值.请参见 ggplot2-大小单位,以除以2.834646的值来校正字体大小

  base = 6#设置图形(和字体)的高度expand = 2#字体大小增加(目前任意设置为2)ggplot(df,aes(x,y))+geom_text(aes(label = label),size = base * expand/2.834646)+scale_x_discrete(position ="top")+主题(axis.text.x = element_text(角度= 90,高度= 0,尺寸=基*展开),axis.text.y = element_text(大小=基本* expand))ggsave("test_large.png",宽度=基础* 2,高度=基础,单位="in",dpi = 300) 

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:

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

12'' x 6'' output

however if I increase dimensions to 36'' x 18'' the fonts are unreadble:

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

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.

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) 

这篇关于将字体大小调整为绘图设备的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆