2013-09-30 63 views
1

是否有在ggplot2的方式,要麼有一種方法在一個GGPLOT2居中文本

  1. 編程訪問x和y軸的範圍爲網格區域或
  2. geom_text居中文本中繪圖區的中間

testData <- data.table(a = c(1,2,3,4), b=rnorm(100, 1, 3), c=rnorm(100)) 
ggplot(testData) + geom_point(aes(x=a, y = b)) + geom_text(aes(x=a, y = 0, label="label")) 

我想避免必須手動設置y軸的範圍,因爲我自動生成大量圖表,並且傾向於使用ggplot2確定正確的範圍。

+0

你試過'hjust'嗎? – Ananta

回答

5

這是你想要的東西:

g1 <- ggplot(testData) + 
    geom_point(aes(x = a, y = b)) + 
    geom_text(aes(x = a, y = mean(range(b)), label="label")) 

g1 

enter image description here

和Q1,如果你要訪問的範圍繪圖區:

# build plot object for rendering 
gg1 <- ggplot_build(g1) 

gg1$panel$ranges[[1]]$x.range 
gg1$panel$ranges[[1]]$y.range 

# mid-point of y-range from plot object 
mean(gg1$panel$ranges[[1]]$y.range) 
# [1] 0.5517525 

# mid-point used in plot above 
with(testData, y = mean(range(b))) 
# [1] 0.5517525 
3

類似的@Henrik想法使用y中值,但我也會使用ylimscale_y_continuous手動設置y限制:

y.ranges <- c(-100,100) 
ggplot(testData,aes(x=a, y = b)) + 
    geom_point() + 
    scale_y_continuous(limits = y.ranges) + 
    geom_text(aes(x=a, y =mean(range(y.ranges)) , label="label")) 
相關問題