R语言ggplot2画图3
程序员文章站
2022-07-14 20:56:33
...
geom_label()和ggplot_Text()的使用详解
主要是用于在图中标注文本
??geom_label()可以查看其帮助文档
##Examples
p <- ggplot(mtcars, aes(wt, mpg, label = rownames(mtcars)))###建立一个新的画板,标记mtcars的行名
p + geom_text()##展示待标记的文本内容,待标记的文本坐标是(wt,mpg) 见图1
# Labels with background
p + geom_label(aes(fill = factor(cyl)), colour = "white",family = "Times New Roman", fontface = "bold",check_overlab=TRUE) ###带背景标注,背景填充白色,新罗马黑体字体,重叠去除,见图2
# Set aesthetics to fixed value
p + geom_point(color="green",aes(size = wt),pch=8) + ##点的颜色为绿色,点的大小按照wt进行分配
geom_text(hjust = 0, nudge_x = 0.05,##标注的水平方向调整为0,x向右移0.05
vjust = 0, nudge_y = 0.5,aes(colour = factor(cyl)),##标注的垂直方向调整为0,y向上移0.05
angle=45,family = "Times New Roman",check_overlap = TRUE,fontface ="bold")+ ##标记的倾角为45°,标记的字体(family)选择新罗马字体(fontface)黑体,有重叠的标记去掉
scale_colour_discrete(l = 40) 见图3
# Scale height of text, rather than sqrt(height)
p + geom_text(aes(size = wt)) +scale_radius(range = c(3,6))
####标注不同的符号及公式
p + geom_point()+geom_text(aes(label = paste(wt, "^(", cyl, ")", sep = ""),hjust = 0, nudge_x = 0.05,###其中的paste 函数的使用
vjust = 0, nudge_y = 0.5,colour = factor(cyl),size=wt,check_overlap = TRUE),parse = TRUE)+annotate("text", label = "plot mpg vs. wt", x = 2, y = 15, size = 8, colour = "red")###添加文本注释 ,标签为plot mpg vs. wt,x和y分别是添加的标签的中心位置 ,大小为8 ,颜色为红色 见图4
# Aligning labels and bars --------------------------------------------------
df <- data.frame(
x = factor(c(1, 1, 2, 2)),
y = c(1, 3, 2, 1),
grp = c("a", "b", "a", "b")
)
# ggplot2 doesn't know you want to give the labels the same virtual width
# as the bars:
ggplot(data = df, aes(x, y, group = grp)) +
geom_col(aes(fill = grp), position = "dodge") +
geom_text(aes(label = y, y = y + 0.05), position = position_dodge(0.9),vjust=-1)##标签按照y 添加,添加的位置在dodge的0.9(中间或者1),vjust调整垂直方向(1,向图形内部移,负值向图形外部移动) 见图5
###position_dodge表示按照grp因子分开作图,position_stack()表示按照因子堆积作图
ggplot(data = df, aes(x, y, group = grp)) +
geom_col(aes(fill = grp)) +
geom_text(aes(label = y), position = position_stack(vjust = 0.5))见图6
# Justification -------------------------------------------------------------
df <- data.frame(
x = c(1, 1, 2, 2, 1.5),
y = c(1, 2, 1, 2, 1.5),
text = c("bottom-left", "bottom-right", "top-left", "top-right", "center") ##标记一组标签
)
ggplot(df, aes(x, y)) +
geom_text(aes(label = text), vjust = "inward", hjust = "inward",colour="blue")##调整标签在途中的位置,向内部调整 见图7
图1
图2
图3
图4
图5
图6
图7