【问题标题】:ggplot2 R fix x-axis label at a specific point relative to plotggplot2 R 在相对于绘图的特定点修复 x 轴标签
【发布时间】:2021-01-07 16:31:54
【问题描述】:

假设我有这样的情节:

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

【问题讨论】:

    标签: r ggplot2 label axis fixed


    【解决方案1】:

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

    【讨论】:

    • 也感谢您的回复!正如你所说,我决定选择 Gregor's,因为它更干净一些。
    • 这是实际使用数据坐标的好方法 - +1。但是,您正在过度绘制(因此标签的奇怪粗体外观)。为避免这种情况,请在geom_text 中设置check_overlap = TRUE,或考虑改用annotate(geom = "text", ...)。 (annotate 可能是更规范的方式。)
    【解决方案2】:

    这不是您想要的,但您可以在theme 选项中调整水平对齐方式。这是 relative 介于 0 和 1 之间,与数据坐标无关。 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))
    

    【讨论】:

    • 谢谢格雷戈尔!这应该可以解决问题!
    猜你喜欢
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2020-07-08
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2022-08-13
    • 2018-05-25
    相关资源
    最近更新 更多