gpt4 book ai didi

r - 有没有办法在 ggplot2 中将文本居中

转载 作者:行者123 更新时间:2023-12-02 15:35:05 26 4
gpt4 key购买 nike

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

最佳答案

这是你想要的吗:

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

关于r - 有没有办法在 ggplot2 中将文本居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19103646/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com