2016-04-11 44 views
1

ggplot()函數及其上構建的任何內容均忽略全局點大小。但是,功能如plot()text()不會。前面的函數預期字體大小以絕對項指定,通過size參數,而後者使用cex,它進行相對縮放。R中的相對和絕對字體大小:混合native和ggplot2方法

並不總是可以避免混合這些機制。這裏有一個例子:你想繪製一系列多邊形並在其中放置標籤,通常用於地圖。尤其對於高度非凸的多邊形,您可能需要使用rgeos::polygonsLabel()(而不是coordinates())來確定適當的標籤位置。此功能建立在text()的頂部,因此,只允許您傳遞相對字體大小。但是,也許您以後想要將標籤從ggplot2包裝中放入geom_text();爲了獲得rgeos::polygonsLabel()輸出的最佳效用,字體大小需要在這裏匹配。

回答

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

sample plot