为什么向ggplot2添加geom_text这么慢?

问题描述 投票:0回答:1

我在使用

ggplot2
绘制十六进制图时发现了一个问题。当我使用
geom_text
向图表添加文本时,需要很长时间!

我做了一个最小的、独立的、可重现的例子,你可以很容易地找到这个问题。

library(ggplot2)
d1 <- ggplot(diamonds, aes(carat, price)) + 
  geom_hex()
d2 <- d1+ 
  geom_text(x=3,y=5000,
            label="y = 0.0243x + 0.298\nR^2 = 0.648, p < 2.2e-16")

system.time({
  print(d1)
})
#   user  system elapsed 
#   0.11    0.01    0.13

system.time({
  print(d2)
})
#   user  system elapsed 
#   0.75    2.84    3.61 

对于极少量的数据,

geom_text
使运行时间延长27倍以上。对于我的真实代码,它将运行时间从 3.65 秒增加到 162.30 秒超过 44 倍,请注意,这只是当运行完成时,需要更多时间才能显示在窗格中)。

我不太确定是什么原因造成的,但我觉得向图形添加文本应该是更基本的图形设置之一,所以我真诚地希望这个问题可以得到解决。另外,由于这个超长时间的运行有时,当我想停止运行时,它经常会导致R崩溃(这让我非常沮丧)。我也很好奇是否有更合适的方式来结束正在运行的进程并保持R程序正常运行。

r ggplot2 geom-text
1个回答
0
投票

这里实际发生的事情是,您正在为每个六边形创建一个字符串副本。看到这一点的一种方法是

将这两个图再现为 svg 字符串
。您将看到 geom_text() 字符串包含以下数百行重复内容:
d2

对于这种事情你应该使用
<text x='404.35' y='510.41' text-anchor='middle' style='font-size: 11.04px; font-family: "Arimo";' textLength='144.40px' lengthAdjust='spacingAndGlyphs'>R^2 = 0.648, p &lt; 2.2e-16</text> <text x='404.35' y='494.51' text-anchor='middle' style='font-size: 11.04px; font-family: "Arimo";' textLength='115.77px' lengthAdjust='spacingAndGlyphs'>y = 0.0243x + 0.298</text> <text x='404.35' y='510.41' text-anchor='middle' style='font-size: 11.04px; font-family: "Arimo";' textLength='144.40px' lengthAdjust='spacingAndGlyphs'>R^2 = 0.648, p &lt; 2.2e-16</text> <text x='404.35' y='494.51' text-anchor='middle' style='font-size: 11.04px; font-family: "Arimo";' textLength='115.77px' lengthAdjust='spacingAndGlyphs'>y = 0.0243x + 0.298</text>

:

annotate()

这只会生成一次文本,因此不会导致此问题:

d3 <- d1 + annotate( "text", x = 3, y = 5000, label = "y = 0.0243x + 0.298\nR^2 = 0.648, p < 2.2e-16" )

© www.soinside.com 2019 - 2024. All rights reserved.