问题描述
library(ggplot2)
dat <- data.frame(x = 1:10,y = 1:10)
ggplot(dat,aes(x = x,y = y)) +
geom_point() +
xlab("Test label")
ggplot2
是否允许将 xlab
定位在特定点?假设我希望标签以 x = 7
为中心显示(而不是默认居中)。
解决方法
这是另一种方式,但@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
这不是您想要的,但您可以在 theme
选项中调整水平对齐方式。这是 0 和 1 之间的相对,与数据坐标无关。 0
左对齐(轴的左侧),1
右对齐,默认 0.5
居中。在这种情况下,我们可以设置 hjust = 0.7
。 (虽然从 1 到 10 的轴的长度为 10 - 1 = 9,所以我们可以挑剔并使用 (7 - 1) / (10 - 1) = 2/3
...我会留给你你想要的精确度。)
ggplot(dat,y = y)) +
geom_point() +
xlab("Test label") +
theme(axis.title.x = element_text(hjust = 0.7))