ggplot2 分面图等添加注释文字,想加哪里加哪里: 自定义函数 AddText()

如果分面图上还想再添加文字,只能使用底层的grid包了。

整个图左下角是原点,向上、向右是正方向,宽高都标准化到[0, 1]之间。

函数定义

#' Add text to ggplot2 figures
#'
#' @param label text you want to put on figure
#' @param x position x, left is 0, right 1
#' @param y position y, bottom is 0, up 1
#' @param color text color
#' @param size font size
#'
#' @return
#' @export
#'
#' @examples
AddText=function(label="RNA cluster",x = 0.18,y = 0.035, color="red", size=12){
  library(grid)
  grid.text(label=label, x = x, y = y, 
            gp=gpar(col=color, fontsize=size,
                    draw=TRUE,just = "centre"))
}

例1:

在ggplot后执行,注意,不能是+号连接!
ggplot(mtcars, aes(mpg, wt)) + geom_point(); AddText("my note")

效果:
在这里插入图片描述

例2:

  p1=ggplot(mtcars, aes(mpg, wt)) + geom_point() + theme_classic()
  print(p1)
  print(AddText("my note"))
  print(AddText("another text", x=0.7, y=0.8, color = "navy"))

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值