问题
ggplot2
期望美学与数据长度相同.geom_text()
把你的字符串重复到每一行数据.我们可以看看ggplot2
与ggplot2::ggplot_build()
一起使用的数据:
dat <- ggplot_build(d2)
lapply(dat$data, head,2)
# [[1]]
# fill x y width height density ndensity count ncount PANEL group colour linewidth linetype alpha
# 1 #132B43 0.3206657 -0.000001 0.1603333 616.5667 1.853912e-05 0.0001721467 1 0.0001721467 1 -1 NA 0.5 1 NA
# 2 #53ABEE 0.2404990 533.962395 0.1603333 616.5667 1.030033e-01 0.9564468928 5556 0.9564468928 1 -1 NA 0.5 1 NA
# [[2]]
# PANEL group colour size angle hjust vjust alpha family fontface lineheight x y label
# 1 1 -1 black 3.88 0 0.5 0.5 NA 1 1.2 3 5000 y = 0.0243x + 0.298\nR^2 = 0.648, p < 2.2e-16
# 2 1 -1 black 3.88 0 0.5 0.5 NA 1 1.2 3 5000 y = 0.0243x + 0.298\nR^2 = 0.648, p < 2.2e-16
第一个数据帧包含每个六边形的坐标.第二个包含相同的文本,重复了53,940次(行数为diamonds
).
一种方法是reproduce both plots as svg strings.你会看到d2
字符串包含以下两行重复了nrow(diamonds)
次:
<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 < 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>
当你看图时,你看不到额外的107,880行,因为每次文本都是在自己上面绘制的.然而,渲染将需要更长的时间.如果以描述如何渲染图的格式保存图,例如svg,它会大得多(20mb与85kb相比).但是,如果你把它保存为像素的表示,例如png,你将不会观察到任何差异.
溶液
您不想将文本映射到您的数据,因此对于这种情况,您应该使用ggplot2::annotate()
.正如doctor 所说,
几何体的属性不是从数据帧的变量映射的,而是作为向量传递.这对于添加小注释(如文本标签)非常有用.
d3 <- d1 + annotate(
"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(d3))
# user system elapsed
# 0.141 0.000 0.141
类似地,与20mb的d2.svg
不同,d3
保存到svg时的大小为85kb,与d1
相同.