ggplot2 texts : Add text annotations to a graph in R software
ggplot2文本:图中添加文本注释
本文介绍如何向使用ggplot2程序包生成的绘图添加文本注释。
geom_text():直接将文本添加到绘图中
geom_label():在文本下方绘制一个矩形,使其更易于阅读。
annotate():用于在绘图上的特定位置添加小文本注释
comment_custom():添加在每个面板中都相同的静态注释
也可以使用R包ggrepel,它是扩展程序,并为ggplot2提供了geom功能,以防止重叠的文本标签彼此分离。
代码运行如下:
rm(list = ls())
# Subset 10 rows
set.seed(1234)
ss <- sample(1:32, 10)
df <- mtcars[ss, ]
head(df)
# Text annotations using geom_text and geom_label
library(ggplot2)
sp <- ggplot(df, aes(x=wt, y=mpg, label = rownames(df))) +
geom_point()
# Add texts
sp + geom_text()
# Change the size of the texts
sp + geom_text(size = 6)
# Change vertical and horizontal adjustment
sp + geom_text(hjust = 0, vjust = 0)
# Change fontface. Allowed values : 1(normal),
# 2(bold), 3(italic), 4(bold.italic)
sp + geom_text(aes(fontface=2))
sp + geom_text(family = "Times New Roman")
sp + geom_label()
#Change the text color and size by groups
sp2 <- ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars)))+
geom_point()
# Color by groups
sp2 + geom_text(aes(color=factor(cyl)))
# Set the size of the text using a continuous variable
sp2 + geom_text(aes(size=wt))
# Define size range
sp2 + geom_text(aes(size=wt)) + scale_size(range=c(3,6))
#Add a text annotation at a particular coordinate
# Solution 1
sp2 + geom_text(x=3, y=30, label="Scatter plot")
# Solution 2
sp2 + annotate(geom="text", x=3, y=30, label="Scatter plot",
color="red")
# ggrepel: Avoid overlapping of text labels
# Use ggrepel::geom_text_repel
require("ggrepel")
set.seed(42)
sp + geom_text_repel(aes(label = rownames(df)),
size = 3.5)
sp + geom_label_repel(aes(label = rownames(df),
fill = factor(cyl)), color = 'white',
size = 3.5) +
theme(legend.position = "bottom")
火山图应用:
# 火山图应用
genes <- read.table(file = "C:/Users/Administrator/Documents/volcano.txt", header = TRUE)
genes$Significant <- ifelse(genes$padj < 0.05, "FDR < 0.05", "Not Sig")
ggplot(genes, aes(x = log2FoldChange, y = -log10(pvalue))) +
geom_point(aes(color = Significant)) +
scale_color_manual(values = c("red", "grey")) +
theme(legend.position = "bottom") +
geom_text_repel(
data = subset(genes, padj < 0.05),
aes(label = Gene),
size = 5,
box.padding = unit(0.35, "lines"),
point.padding = unit(0.3, "lines")
)
Rplot03.png
网友评论