Relative positioning of geom_text in ggplot2?

て烟熏妆下的殇ゞ 提交于 2019-11-27 21:33:27

If you know the range of the data in your plot, you can calculate the "true" x and y limits using the fact that ggplot using an additive expansion factor of 0.05 by default, so that the extents of the graph extend just slightly beyond the actual data values.

You can specify and multiplicative and additive expansion factor when specifying scales using expand = c(mult, add) where mult is the multiplicative factor and so on. So the default setting is expand = c(0,0.05).

Yes, it is possible to extract the x and y limits from a ggplot2-plot. This function returns the x and y coordinate of the center of a ggplot2 plot object:

center.position <- function(plot) {
xpos <- (ggplot_build(plot)$panel$ranges[[1]]$x.range[2]-ggplot_build(plot)$panel$ranges[[1]]$x.range[1])/2+ggplot_build(plot)$panel$ranges[[1]]$x.range[1]
ypos <- (ggplot_build(plot)$panel$ranges[[1]]$y.range[2]-ggplot_build(plot)$panel$ranges[[1]]$y.range[1])/2+ggplot_build(plot)$panel$ranges[[1]]$y.range[1]
return(data.frame(x=xpos,y=ypos))
}

If your x-Data is in POSIXct-format, you still have to transform it:

center.coords <- center.position(myplot)
myplot <- myplot + annotate("text",x=as.POSIXct(center.coords$x,origin="1970-01-01"), y=center.coords$y, label="X")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!