首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

ggplot2-annotation|画图点“精”,让图自己“解释”

可视化的展示方式可以使数据更易读,且容易看出一些数据下隐藏的“结果”,而添加注释则可以进一步聚焦到想重点展示的“信息”。

一 绘制基础图

library(ggplot2)
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point()

更多参数ggplot2|详解八大基本绘图要素,主题ggplot2|theme主题设置,详解绘图优化-“精雕细琢”,图例ggplot2 |legend参数设置,图形精雕细琢 可参考。

二 添加“注释”

2.1 添加文字标签

1) 通过x y 指定标签的位置

p + annotate("text", x = 4, y = 25, label = "add text",
             color="orange",size = 5, angle=45, fontface="bold" )

2) 生成注释数据集,然后添加

annotation <- data.frame(
  x = c(2,4),
  y = c(20,25),
  label = c("label 1", "label 2")
)

A:geom_text方式添加

p + geom_text(data=annotation, aes( x=x, y=y, label=label))

B:geom_label方式添加

p + geom_label(data=annotation, aes( x=x, y=y, label=label),                
               color="blue", size=5 , angle= 60, fontface="bold" )

如果待注释的text太多,可使用ggrepel包解决标签太多导致的重叠问题

ggplot2-plotly|让你的火山图“活”过来

2.2 点注释

1)添加点

p + annotate(geom = "point", x = 4, y = 25, colour = "orange", size = 5)

2)更改原有点

对齐数据集中数据坐标即可

p + annotate(geom = "point", x = 2.620, y = 21.0, colour = "red", size = 5)

3)想在原有点外加一个圈,怎么办呢?

p + 
  annotate(geom = "point", x = 2.620, y = 21.0, colour = "red", size = 3) + 
  annotate(geom = "point", x = 2.620, y = 21.0)

额,,我想到的是图层叠加,有其他办法的欢迎告知

4)pointrange添加点及range

p + annotate("pointrange", x = 3.5, y = 20, ymin = 12, ymax = 28,
             colour = "orange", size = 1.5, alpha=0.6)

2.3 线 , 矩形注释

1) 添加矩形,给出边的范围

p + annotate("rect", xmin=2, xmax=3, ymin=20 , ymax=30,
             alpha=0.2, color="blue", fill="blue")

2)添加线段,给出两端点位置

p + annotate("segment", x = 1, xend = 3, y = 25, yend = 15,
             colour = "purple", size=3, alpha=0.6)

3)线段加箭头,给出两端点位置

p + annotate("segment", x = 2, xend = 4, y = 15, yend = 25,
             colour = "pink", size=3, alpha=0.6,
             arrow=arrow())

曲线加箭头?

p + annotate("curve", x = 4, xend = 2.620, y = 30, yend = 21.0,
             colour = "blue", curvature = .3, arrow = arrow(length = unit(2, "mm"))
) + annotate(geom = "text", x = 4.1, y = 30.1, label = "关注这个点?", hjust = "left")

2.4 添加垂直线

p + geom_hline(yintercept=25, color="orange", size=1) + geom_vline(xintercept=3, color="orange", size=1)

2.5 添加轮廓图

library(ggforce)
library(concaveman)
ggplot(mpg, aes(displ, hwy,col = cyl)) +
  geom_point() + geom_mark_hull(aes(label = cyl, group = cyl),
                   show.legend = FALSE, expand = unit(3, "mm")) +
  theme_no_axes()
下一篇
举报
领券