简体   繁体   English

gomplot2中geom_text的相对定位?

[英]Relative positioning of geom_text in ggplot2?

I am using geom_text to annotate plots in gglot2 and I want use relative positioning rather than absolute. 我使用geom_text来注释geom_text中的gglot2 ,我想使用相对定位而不是绝对。 That is, I want a position of (0.5, 0.5) to be dead center regardless of the x and y axis limits. 也就是说,无论x轴和y轴的限制如何,我都希望(0.5, 0.5)的位置为死点。 Is that possible? 那可能吗?

Alternatively I could of course transform a relative position to an absolute one if I had the x and y limits. 或者,如果我有x和y限制,我当然可以将相对位置转换为绝对位置。 Is it possible to extract those from a plot? 是否有可能从情节中提取出来?

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. 如果您知道绘图中数据的范围,则可以使用ggplot默认情况下使用0.05的加法扩展因子来计算“真实”x和y限制,以便图形的范围仅略微超出实际数据值。

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. 使用expand = c(mult, add)指定比例时,可以指定和乘法和加法扩展因子expand = c(mult, add)其中mult是乘法因子,依此类推。 So the default setting is expand = c(0,0.05) . 因此默认设置为expand = c(0,0.05)

Yes, it is possible to extract the x and y limits from a ggplot2-plot. 是的,可以从ggplot2-plot中提取x和y限制。 This function returns the x and y coordinate of the center of a ggplot2 plot object: 此函数返回ggplot2绘图对象中心的x和y坐标:

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: 如果您的x-Data是POSIXct格式,您仍然需要对其进行转换:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM