有没有办法在ggplot2中居中文本

时间:2013-09-30 20:54:19

标签: r ggplot2

ggplot2中有没有办法,

  1. 以编程方式访问网格区域的x和y轴范围或
  2. 告诉geom_text将文字置于情节区域中间
  3. 实施例

    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确定正确的范围。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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"))
相关问题