R中的相对和绝对字体大小:混合本机和ggplot2方法 [英] Relative and absolute font sizes in R: Mixing native and ggplot2 methods

查看:139
本文介绍了R中的相对和绝对字体大小:混合本机和ggplot2方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ggplot()函数以及基于它的任何内容都将忽略全局磅值.但是,像plot()text()这样的函数却没有.前一个函数希望通过size参数以绝对的方式指定字体大小,而后一个函数则与cex一起使用,后者可以进行相对缩放.

The ggplot() function and anything built on top of it ignores the global point size. Functions like plot() and text(), however, do not. The former functions expect font sizes to be specified in absolute terms, through a size parameter, while the latter work with cex, which does relative scaling.

并非总是可以避免将这些机制混在一起.这是一个示例:您想绘制一系列多边形并将标签放置在其中,通常用于地图.特别是对于高度非凸的多边形,您可能需要使用rgeos::polygonsLabel()(而不是coordinates())来确定适当的标签位置.此功能建立在text()的基础上,因此,再次只能允许您传递相对字体大小.但是也许以后您想在ggplot2软件包中使用geom_text()放置标签;为了实现rgeos::polygonsLabel()输出的最佳效用,字体大小需要在此处匹配.

It's not always possible to avoid mixing those mechanisms. Here's an example: You want to plot a series of polygons and place labels inside them, typically for a map. Especially for highly nonconvex polygons, you might want to use rgeos::polygonsLabel() (rather than, say, coordinates()) to determine appropriate label positions. This function is built on top of text() and thus, again, only allows you to pass relative font sizes. But maybe you later want to place the labels with geom_text() from the ggplot2 package; for optimal utility of the rgeos::polygonsLabel() output, font sizes need to match here.

推荐答案

我发现以下示例可以正常工作,并且希望与大家分享,因为花了我一些时间才能实现.如果我在做我不应该做的事情,例如,请纠正我.点到毫米的转换.为此,我将创建一个PNG图像文件,以便与该网站兼容,例如SVG和PDF也可以正常工作.

I've found the following example to work as expected and would like to share it since it took me a while to get there. Please correct me if I'm doing something that I shouldn't be, e.g. with the point-to-mm conversion. I'll create a PNG image file for this compatibility with this site but, e.g., SVG and PDF work just as well.

pointSize <- 20 # or whatever you want

# Setting point size here affects the native plotting methods
# like text()
png('myfigure.png', pointsize=pointSize) # apparent default: 12

library(ggplot2)
plot.new()

pointToMM = function(x) 0.352778*x

# plot a few 'o's
p <- ggplot(mtcars, aes(wt, mpg, label = 'o')) +
  geom_text(size = pointToMM(pointSize)) # apparent default: pointToMM(11)

# label the axes in the same
p <- p + labs(x = 'xo xo xo xo xo xo', y = 'xo xo xo xo xo xo') +
  theme_bw(pointSize) # apparent default: 12

print(p)

# Add 'xo' in two places. Notice how the sizes match up.
# The x and y coordinates were chosen ad-hoc for this example
text(0.35,0.13, 'xo')
text(0.5, 0.0, 'xo')

dev.off()

这篇关于R中的相对和绝对字体大小:混合本机和ggplot2方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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