[英]ggplot2 R fix x-axis label at a specific point relative to plot
Say I have a plot like this:假设我有这样的 plot:
library(ggplot2)
dat <- data.frame(x = 1:10, y = 1:10)
ggplot(dat, aes(x = x, y = y)) +
geom_point() +
xlab("Test label")
Does ggplot2
allow for fixing the xlab
positioning at a specific point? ggplot2
是否允许将xlab
定位固定在特定点? Say I wanted the label to appear centered at the point where x = 7
(rather than the default centering).假设我希望 label 出现在
x = 7
的中心(而不是默认的中心)。
Here is another way, but the one from @Gregor Thomas is nicer这是另一种方式,但来自@Gregor Thomas 的方式更好
library(ggplot2)
dat <- data.frame(x = 1:10, y = 1:10, label = 'Test label')
p <- ggplot(dat, aes(x = x, y = y)) +
geom_point() +
xlab('') # no x-label
#xlab("Test label")
p + geom_text(aes(label = label, x = 7, y = -Inf), vjust = 3) +
coord_cartesian(clip = 'off') # This keeps the labels from disappearing
This isn't exactly what you want, but you can adjust the horizontal justification in the theme
options.这不完全是您想要的,但您可以在
theme
选项中调整水平对齐方式。 This is relative between 0 and 1, not tied to the data coordinates.这是 0 和 1 之间的相对值,与数据坐标无关。
0
is left-justified (left side of the axis), 1
is right-justified, and the default 0.5
as centered. 0
左对齐(轴的左侧), 1
右对齐,默认0.5
居中。 In this case, we can set hjust = 0.7
.在这种情况下,我们可以设置
hjust = 0.7
。 (Though an axis from 1 to 10 has length 10 - 1 = 9, so we could get nitpicky and use (7 - 1) / (10 - 1) = 2/3
... I'll leave it to you how precise you want to be.) (虽然从 1 到 10 的轴的长度为 10 - 1 = 9,所以我们可以挑剔并使用
(7 - 1) / (10 - 1) = 2/3
...你想成为。)
ggplot(dat, aes(x = x, y = y)) +
geom_point() +
xlab("Test label") +
theme(axis.title.x = element_text(hjust = 0.7))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.