【问题标题】:How can I add annotations below the x axis in ggplot2?如何在 ggplot2 的 x 轴下方添加注释?
【发布时间】:2015-09-13 18:19:39
【问题描述】:

我有以下图表:

library(ggplot2)
library(scales)
library(magrittr)
df1 <-
  structure(
    list(
      x = structure(
        1:5, .Label = c("5", "4", "3", "2",
                        "1"), class = "factor"
      ), y = c(
        0.166666666666667, 0.361111111111111,
        0.0833333333333333, 0.222222222222222, 0.291666666666667
      )
    ), .Names = c("x",
                  "y"), row.names = c(NA,-5L), class = c("tbl_df", "tbl", "data.frame"), drop = TRUE
  )

df1 %>% ggplot(aes(x , y )) + geom_bar(stat = "identity") +
  scale_y_continuous(labels = percent) 

我想在 5 和 1 下方添加两行注释,粗体文本。例如,“最高\nvalue”低于 5,“最低 \nvalue”低于 1。

我尝试了geom_text,但无法将文本放置在我想要的位置。

【问题讨论】:

标签: r ggplot2


【解决方案1】:

这可以使用annotation_custom() 来完成。我正在从this answer 绘图。

难点在于ggplot 剪裁了放置在绘图区域之外的注释,这是您想要做的。但剪裁可以关闭。

annotation_custom() 使用 grobs,因此您首先需要创建它们:

library(grid)
text_high <- textGrob("Highest\nvalue", gp=gpar(fontsize=13, fontface="bold"))
text_low <- textGrob("Lowest\nvalue", gp=gpar(fontsize=13, fontface="bold"))

接下来,您设置绘图并存储它:

p <-
df1 %>% ggplot(aes(x , y )) + geom_bar(stat = "identity") +
   scale_y_continuous(labels = percent) +
   theme(plot.margin = unit(c(1,1,2,1), "lines")) +
   annotation_custom(text_high,xmin=1,xmax=1,ymin=-0.07,ymax=-0.07) + 
   annotation_custom(text_low,xmin=5,xmax=5,ymin=-0.07,ymax=-0.07)

第三行确保图下方有足够的空间放置标签,最后两行添加注释。位置以两个坐标的最小值和最大值给出。 grob 将以这些坐标定义的区域为中心。在目前的情况下,通过将最小值和最大值设置为相同来简单地定义一个点似乎是最简单的。

最后一步是关闭裁剪,以便绘图区域之外的对象(即注释)也被绘制。对于 ggplot2 3.0.0 和更新版本,这可以使用 coord_cartesian() 来完成(参见 answer by tfad334):

p + coord_cartesian(clip = "off")

对于旧版本的 ggplot2,过程稍微复杂一些:

gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)

最后一行画出情节。

【讨论】:

    【解决方案2】:

    使用ggplot2 3.0.0 版,您将不需要gtable 在 Stibu 的回答中关闭剪裁。使用coord_cartesian() 来实现同样的事情:

    library(gridExtra)
    df1 %>% ggplot(aes(x , y )) + geom_bar(stat = "identity")+
    scale_y_continuous(labels = percent)+
    theme(plot.margin = unit(c(1,1,2,1), "lines")) +
    annotation_custom(text_high,xmin=1,xmax=1,ymin=-0.07,ymax=-0.07) + 
    annotation_custom(text_low,xmin=5,xmax=5,ymin=-0.07,ymax=-0.07)+
    coord_cartesian(ylim=c(0,0.35), clip="off")
    

    【讨论】:

      猜你喜欢
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 2014-04-12
      • 2021-06-21
      相关资源
      最近更新 更多