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

Ign*_*cio 10 r 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) 
Run Code Online (Sandbox Code Playgroud)

我想在5和1之下添加带有粗体文本的两行注释.例如,'最高\nvalue'低于5,'最低\n值'低于1.

我试过geom_text但我不能把文字放在我想要的地方.

Sti*_*ibu 17

这可以使用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"))
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

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

最后一步是关闭剪裁,以便绘制绘图区域外的对象(即注释).对于ggplot2 3.0.0和更新版本,这可以使用coord_cartesian()(参见tfad334答案):

p + coord_cartesian(clip = "off")
Run Code Online (Sandbox Code Playgroud)

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

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

最后一行描绘了情节.

在此输入图像描述


tfa*_*334 6

使用ggplot23.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")
Run Code Online (Sandbox Code Playgroud)