首页 > 解决方案 > 如何在ggplot2中自动获取绘图的中心位置

问题描述

我尝试使用 ggplot2 在我的绘图中添加 R 平方值。

我想把这个值放在这个图的中心位置。

有人能告诉我如何自动获取中心位置(我的代码中的 xposition 和 yposition 值)吗?因为我要制作一堆图,所以我需要自动获取这两个值。

下面是我的代码:

xposition   <-  2.5
yposition   <-  2.5

plotdata    <-  data.frame(x=1:10,y=2*(1:10))
relation    <-  lm(plotdata$y ~ plotdata$x)
lb          <-  paste("R^2 == ",round(summary(relation)$r.squared,2))
pp          <-  ggplot(data=plotdata,aes(x=x, y=y)) + geom_point(colour="blue",size=1.5)
pp          <-  pp + geom_smooth(method = "lm", se = FALSE)
pp          <-  pp + annotate("text",x=xposition,y=yposition,label=lb, parse=TRUE,size=6)

标签: rggplot2

解决方案


中心图

这是您正在寻找的东西吗?

pp + annotation_custom(grid::textGrob(lb), + xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)

annotation_custom是应该找到中心位置的函数。


推荐阅读