【问题标题】:Relative and absolute font sizes in R: Mixing native and ggplot2 methodsR 中的相对和绝对字体大小:混合原生和 ggplot2 方法
【发布时间】:2016-08-01 13:11:57
【问题描述】:
ggplot() 函数以及在它之上构建的任何东西都会忽略全局点大小。但是,plot() 和 text() 之类的函数却没有。前一个函数希望通过size 参数以绝对值指定字体大小,而后者使用cex,它会进行相对缩放。
避免混合这些机制并不总是可能的。这是一个示例:您想要绘制一系列多边形并在其中放置标签,通常用于地图。特别是对于高度非凸多边形,您可能希望使用rgeos::polygonsLabel()(而不是coordinates())来确定适当的标签位置。这个函数建立在text() 之上,因此,同样,只允许您传递相对字体大小。但也许你以后想从 ggplot2 包中放置带有geom_text() 的标签;为了获得rgeos::polygonsLabel() 输出的最佳效用,这里的字体大小需要匹配。
【问题讨论】:
标签:
r
text
ggplot2
font-size
【解决方案1】:
我发现以下示例按预期工作,并想分享它,因为我花了一段时间才到达那里。如果我正在做一些我不应该做的事情,请纠正我,例如通过点到毫米的转换。我将创建一个 PNG 图像文件以实现与本网站的兼容性,但例如 SVG 和 PDF 也可以。
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()