前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >R语言之可视化(20)之geom_label()和geom_text()

R语言之可视化(20)之geom_label()和geom_text()

作者头像
用户1359560
发布2019-02-22 15:21:01
35.2K1
发布2019-02-22 15:21:01
举报
文章被收录于专栏:生信小驿站生信小驿站

Geom_text()将文本直接添加到绘图中。 geom_label()在文本后面绘制一个矩形,使其更易于阅读。

示例

代码语言:javascript
复制
p <- [ggplot](mtcars, aes(wt, mpg, label = rownames(mtcars)))
p + geom_text()

image

避免字体重叠

p + geom_text(check_overlap = TRUE)

image

给label加上背景

p + geom_label()

image

修改字体大小

p + geom_text(size = 10)

image

p + geom_point() + geom_text(hjust = 0, nudge_x = 0.05)

image

p + geom_point() + geom_text(vjust = 0, nudge_y = 0.5)

image

p + geom_point() + geom_text(angle = 45)

image

添加映射

p + geom_text(aes(colour = factor(cyl)))

image

p + geom_text(aes(colour = factor(cyl))) + scale_colour_discrete(l = 40)

image

p + geom_label(aes(fill = factor(cyl)), colour = "white", fontface = "bold")

image

p + geom_text(aes(size = wt))

image

缩放文本高度

p + geom_text(aes(size = wt)) + scale_radius(range = c(3,6))

image

可以通过设置parse = TRUE来显示表达式。themama中描述了显示的详细信息,但请注意geom_text使用字符串,而不是表达式。

p + geom_text(aes(label = paste(wt, "^(", cyl, ")", sep = "")), parse = TRUE)

image

添加一个注释

p +geom_text() +annotate("text", label = "plot mpg vs. wt", x = 2, y = 15, size = 8, colour = "red")

image

对齐标签和条形

df <- data.frame( x = factor(c(1, 1, 2, 2)), y = c(1, 3, 2, 1), grp = c("a", "b", "a", "b") )

ggplot2不知道你想给标签赋予相同的虚拟宽度

ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp), position = "dodge") + geom_text(aes(label = y), position = "dodge")

image

ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp), position = "dodge") + geom_text(aes(label = y), position = position_dodge(0.9))

image

#使用你无法轻推和躲避文字,所以改为调整y位置

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 = 0 )

image

如果将文本放在堆积的条形图中每个条形图的中间,需要设置position_stack()的vjust参数

ggplot(data = df, aes(x, y, group = grp)) + geom_col(aes(fill = grp)) + geom_text(aes(label = y), position = position_stack(vjust = 0.5))

image

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.01.12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 示例
  • 避免字体重叠
  • 给label加上背景
  • 修改字体大小
  • 添加映射
  • 缩放文本高度
  • 添加一个注释
  • 对齐标签和条形
  • ggplot2不知道你想给标签赋予相同的虚拟宽度
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档