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

问题描述

假设我有一个这样的情节:

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))

enter image description here