ggplot2 R 在相对于绘图的特定点固定 x 轴标签

ggplot2 R fix x-axis label at a specific point relative to plot

假设我有这样的情节:

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 的中心位置(而不是默认的中心位置)。

这不是您想要的,但您可以在 theme 选项中调整水平对齐方式。这是 0 和 1 之间的 relative,不依赖于数据坐标。 0为左对齐(轴左侧),1为右对齐,默认0.5为居中。在这种情况下,我们可以设置hjust = 0.7。 (虽然从 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))

这是另一种方式,但来自@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