代码之家  ›  专栏  ›  技术社区  ›  user25445882

ggplot2文本位于上边距,翻转坐标

  •  1
  • user25445882  · 技术社区  · 1 年前

    我想在上边距的绘图中添加一些文本,但在使用coord_flip()后,我能找到的所有解决方案都弄乱了翻转的坐标系

    var1<- c("ab", "cd")
    HR1<-c (0.51, 0.65)
    lower1 <- c(0.4, 0.5)
    upper1 <- c(0.6, 0.9)
    forest1 <- data.frame(var1, HR1, lower1, upper1)
    ggplot(data=forest1, aes(x=var1, y=HR1, ymin=lower1, ymax=upper1)) +
      geom_pointrange() +
      geom_hline(yintercept=1, lty=2) + 
      geom_hline(yintercept=0.4, lty=2) +  
      coord_flip() +  
      xlab("Label") + ylab("Mean (95% CI)") +
      theme_bw() +
      labs(x="", y="HR") + ylim(0.3, 1.1) +
      theme(plot.margin = unit(c(4, 1, 1, 1), "lines")) 
    

    应该像在 image . 有(简单的)解决方案吗? 谢谢

    1 回复  |  直到 1 年前
        1
  •  0
  •   stefan    1 年前

    实现所需结果的一个简单选项是使用辅助轴技巧添加注释,即添加辅助x轴并通过轴文本添加注释。如果你需要一些额外的造型,你可以使用例如。 ggtext .

    注意:我掉了 coord_flip 而是切换 x y .

    library(ggplot2)
    library(ggtext)
    
    ggplot(data = forest1, aes(y = var1, x = HR1, xmin = lower1, xmax = upper1)) +
      geom_pointrange() +
      geom_vline(xintercept = c(.4, 1), lty = 2) +
      scale_x_continuous(
        sec.axis = dup_axis(
          breaks = c(.325, .6, 1.075),
          labels = c("Words", "Words", "**More Words**")
        ),
        limits = c(0.3, 1.1)
      ) +
      theme_bw() +
      labs(x = NULL, y = "HR") +
      theme(
        axis.text.x.top = ggtext::element_markdown(size = 12),
        axis.ticks.x.top = element_blank()
      )