Relative and absolute font sizes in R: Mixing native and ggplot2 methods

我是研究僧i 提交于 2020-01-05 10:34:45

问题


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.

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.


回答1:


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()



来源:https://stackoverflow.com/questions/36547590/relative-and-absolute-font-sizes-in-r-mixing-native-and-ggplot2-methods

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!