如何在 ggplot2 中的 x 轴下方添加注释? [英] How can I add annotations below the x axis in ggplot2?

查看:37
本文介绍了如何在 ggplot2 中的 x 轴下方添加注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下图表:

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 以下用粗体文本添加两行注释.例如,'Highest value' 低于 5,'Lowest value' 低于 1.

I would like to add a two lines note with bold text below 5 and 1. For example, 'Highest value' bellow 5 and 'Lowest value' below 1.

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

I tried geom_text but I cannot place the text where I want.

推荐答案

使用 ggplot2 3.0.0 版,您将不需要 gtable 在 Stibu 中关闭剪辑回答.使用 coord_cartesian() 来达到同样的效果:

With ggplot2 version 3.0.0, you won't need gtable to turn clipping off in Stibu's answer. Use coord_cartesian() to achieve the same thing:

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

这篇关于如何在 ggplot2 中的 x 轴下方添加注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆