gpt4 book ai didi

r - 以特定字体和字体大小计算字符串的宽度(无需在批处理模式下创建任何文件)

转载 作者:行者123 更新时间:2023-12-04 14:50:21 31 4
gpt4 key购买 nike

有一个类似的问题here即要求默认字体大小的字符串宽度。但是,我想计算特定字体和字体大小的文本字符串的宽度。
基础 R strwidth()函数似乎忽略了对字体和系列参数的更改。观察:

  strwidth("This is cool.", units = "inches", font = 12, family = "sans")
# [1] 0.9479167

# font 10 gives same result as font 12
strwidth("This is cool.", units = "inches", font = 10, family = "sans")
# [1] 0.9479167

# monospace font gives same result as sans serif
strwidth("This is cool.", units = "inches", font = 10, family = "mono")
# [1] 0.9479167
所以看起来字体和系列参数没有被函数拾取。
我发现用 par()设置图形参数使 strwidth()功能正常工作:
  par(ps = 12, family = "sans")
strwidth("This is cool.", units = "inches")
# [1] 0.8541667

par(ps = 10, family = "sans")
strwidth("This is cool.", units = "inches")
# [1] 0.7291667

par(ps = 10, family = "mono")
strwidth("This is cool.", units = "inches")
# [1] 1.083333

这些宽度似乎是不错的估计。
现在的问题是 par()正在我的项目中创建空的 PDF 文件,因为没有图形设备传递给它。我的问题是,我没有创建任何图形。我只是想找到字符串的宽度。我不应该设置图形参数来执行此操作。
所以问题仍然存在:如何在 R 中找到特定字体和字体大小的字符串的宽度(不创建任何文件)?

最佳答案

对于批量使用,请考虑对 grDevices 中的文件参数的 pdf 帮助页面中的 Material 进行测试。 -package 默认从作为核心套件一部分安装的基本包加载:

file
a character string giving the file path. If it is of the form "|cmd", the output is piped to the command given by cmd. If it is NULL, then no external file is created (effectively, no drawing occurs), but the device may still be queried (e.g., for size of text).


运行这个我命名为“parwidth.R”的文件:
pdf(NULL) # and this could be opened with additional parameters
par(ps = 12, family = "sans")
strwidth("This is cool.", units = "inches")
dev.off()
...来自与 Rscript parwidth.R 的终端 session ...
不会生成“Rplots.pdf”文件,并且会返回与上述相同的值。我怀疑您最终可能需要查看 pdf 调用的第一个函数的代码。 ,即 getAnywhere(initPSandPDFfonts) .我怀疑它会因操作系统而异。

关于r - 以特定字体和字体大小计算字符串的宽度(无需在批处理模式下创建任何文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69170619/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com