繁体   English   中英

如何在 ggplot2 中的 x 轴下方添加注释?

[英]How can I add annotations below the x axis in ggplot2?

我有以下图表:

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但我无法将文本放在我想要的地方。

这可以使用annotation_custom()来完成。 我正在从这个答案中汲取灵感

难点在于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() (请参阅tfad334答案):

p + coord_cartesian(clip = "off")

使用旧版本的 ggplot2,程序稍微复杂一些:

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

最后一行绘制了情节。

在此处输入图片说明

使用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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM