R语言ggplot2添加单个文本或多个文本(包括公式)

时间:2024-12-16 22:37:29

R语言ggplot2添加单个文本或多个文本

        • 1. 图中添加单个文本(annotate函数,函数)和公式
        • 2. 散点图全部添加文字label

1. 图中添加单个文本(annotate函数,函数)和公式

比如添加TEST字符:

p1 <- ggplot(mtcars, aes(x=mpg, y=wt)) +
  geom_point(color = "grey20",size = 1, alpha = 0.8)
p1 + 
  annotate("text", x = 20 , y = 4,label = "TEST",colour="red") + 
  annotate("text", x = 20 , y = 3,label = "TEST2",colour="blue") + theme_bw()

在这里插入图片描述
这里关注到annotate函数,很好用,还有其他应用:

p1 <- ggplot(mtcars, aes(x=mpg, y=wt)) +
  geom_point(color = "grey20",size = 1, alpha = 0.8)

p1 + 
  annotate("text", x = -4 , y = 1.2,label = "TEST",colour="red") + 
  annotate("text", x = -4 , y = 0.8,label = "TEST2",colour="blue") 


p1
grid.text("text1", x = 0.2, y = 0.8)
grid.text("text2", x = 0.2, y = 0.8)

## annotate examples
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + annotate("text", x = 4, y = 25, label = "Some text")
p + annotate("text", x = 2:5, y = 25, label = "Some text")
p + annotate("rect", xmin = 3, xmax = 4.2, ymin = 12, ymax = 21,
             alpha = .2)
p + annotate("segment", x = 2.5, xend = 4, y = 15, yend = 25,
             colour = "blue")
p + annotate("pointrange", x = 3.5, y = 20, ymin = 12, ymax = 28,
             colour = "red", size = 1.5)

p + annotate("text", x = 2:3, y = 20:21, label = c("my label", "label 2"))

p + annotate("text", x = 4, y = 25, label = "italic(R) ^ 2 == 0.75",
             parse = TRUE)
p + annotate("text", x = 4, y = 25,
             label = "paste(italic(R) ^ 2, \" = .75\")", parse = TRUE)

添加公式:

require(gridExtra)
require(ggplot2)
p=ggplot(data.frame(x=c(-3,3)), aes(x=x)) + stat_function(fun=dnorm)
p1=p + annotate("text", x=2, y=0.3, parse=T, label="y==frac(1, sqrt(2*pi)) * e^{-x^2 / 2}")
p2=p + annotate("text", x=2, y=0.3, parse=T, label="frac(1, sqrt(2*pi)) * e^{-x^2 / 2}")
grid.arrange(p1,p2, nrow=1)

在这里插入图片描述

对于()函数,需要加载grid包,使用体验不如annotate

p1 <- ggplot(mtcars, aes(x=mpg, y=wt)) +
  geom_point(color = "grey20",size = 1, alpha = 0.8)

p1
grid.text("text1", x = 0.2, y = 0.5)
grid.text("text2", x = 0.2, y = 0.8,gp=gpar(col="red"))

详细的功能可以查看函数帮助 ?

2. 散点图全部添加文字label

散点图有需要添加label的需求时候,可以使用ggplot中的geom_text
或者使用ggrepel包中的,可以防止label重叠:

geom_label_repel()
geom_text_repel()

参考:
/english/wiki/ggplot2-texts-add-text-annotations-to-a-graph-in-r-software
/questions/66458560/how-to-add-single-annotation-to-overall-ggplot-plot-and-not-to-each-facet