ggplot2
中有没有办法,
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 :(得分:5)
这就是你想要的:
g1 <- ggplot(testData) +
geom_point(aes(x = a, y = b)) +
geom_text(aes(x = a, y = mean(range(b)), label="label"))
g1
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中值的想法,但我也会使用ylim
或scale_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"))