目的:图中添加文字。
1. 每个点都添加文字
效果不好。
保持文字颜色和点一致,就没法斜体。
设置斜体,就没法保持文字颜色。
library(ggplot2)
p1=ggplot(iris, aes(Sepal.Length, Sepal.Width, color=Species))+
geom_point(size=1.5)+
theme_classic();p1
# try1: 为每个点添加文字:斜体失败
p2 <- p1 + geom_text(aes(label = Species),
vjust = -1, parse = TRUE,
fontface="italic",
family = "Arial"
)+
# 设置P值为斜体
theme(
#text = element_text(face = "italic") #正图不斜体,其他都斜体: 坐标轴tick/label, 图例
); p2
# try2: 斜体文字,但是没有颜色
p2=p1+annotate("text", x=iris$Sepal.Length, y=iris$Sepal.Width,
#color=iris$Species,
color="grey",
vjust=-1,
label=iris$Species,
fontface="italic"); p2
2. annotate 添加少量几个文字信息
annotate是脱离整体数据流的,必须重新制定x和y坐标及标签内容 label。
- hjust 取值范围[0, 0.5, 1] 分别控制水平方向的左对齐,中部对齐,右对齐。
- vjust 同上,控制竖直方向的对齐。
- angle 旋转角度,单位360°一圈。x轴正方向为0,逆时针方向为正角度。
- fontface 斜体、黑体
# https://statisticsglobe.com/add-bold-and-italic-text-to-ggplot2-plot-in-r
p3=ggplot(data=data.frame(x=c(4.5,7.5), y=c(2,4)), aes(x, y))+
geom_point(size=0.1)+
theme_classic()+
annotate(geom="text", x=6, y=2, label="label1 normal", fontface="plain")+ #default fontface is plain
annotate("text", x=6, y=2.2, label="label2 Bold", fontface="bold", color="red")+
annotate("text", x=6, y=2.4, label="label3 italic", fontface="italic", size = 8, color="navy")+
annotate("text", x=6, y=2.6, label="label4 bold and italic", fontface="bold.italic")+
# Add partly bold/italic text element to plot
annotate("text", x=6, y=2.8, label = "label5~bold(Partly~Bold)~and~italic(Partly~Italic)~Text", parse = TRUE)+
annotate("text", x=6, y=3.0, label = "italic(R) ^ 2 == 0.75", parse = TRUE)+
annotate("text", x=6, y=3.2, label = "paste(italic(R) ^ 2, \" = 0.75\")", parse = TRUE, color="purple")+
# http://www.cookbook-r.com/Graphs/Fonts/
annotate("text", x=5, y=3, label = "label6 angle=60", angle=60,
vjust=0, hjust=0,
size=4, #family="Courier",
fontface="bold",color="red")+
ggtitle("annotate text styles"); p3
# http://127.0.0.1:60473/graphics/plot_zoom_png?width=379&height=350
#
# ggtext pkg //todo
# https://genchanghsu.github.io/ggGallery/posts/2021-07-10-post-5-awesome-text-display-with-ggtext/
#labs(title = "<span style = 'font-size: 18pt'><i>**I**nternational **B**iology **O**lympiad<i/></span><br>Numbers of participants over past three decades"); p3