有没有一种方法可以使文本在ggplot2中居中 [英] Is there a way to center text in a ggplot2

查看:167
本文介绍了有没有一种方法可以使文本在ggplot2中居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ggplot2中是否可以找到

  1. 以编程方式访问网格区域或
  2. 的x和y轴范围
  3. 告诉geom_text将文本置于绘图区域的中央
  1. Programmatically access the x and y axis range for the grid area or
  2. Tell geom_text to center text in the middle of the plot area

示例

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

I would like to avoid having to manually set the range of the y axis, since I am generating a large number of charts automatically and would prefer to have ggplot2 determine the right range to use.

推荐答案

这就是您想要的:

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

g1

还有Q1,如果要访问绘图区域的范围:

And Q1, if you want to access the ranges for the plot area:

# 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

这篇关于有没有一种方法可以使文本在ggplot2中居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆