ggplot2 标签
时间: 2023-11-15 14:53:48 浏览: 148
ggplot2是一种用于数据可视化的R语言包。在使用ggplot2进行可视化时,可以使用geom_text函数在图外添加数据点标签和注释。以下是几种在ggplot2中添加标签的方法:
方法1:
```R
library(ggplot2)
library(grid)
df <- data.frame(y = c("cat1", "cat2", "cat3"), x = c(12, 10, 14), n = c(5, 15, 20))
p <- ggplot(df, aes(x, y)) +
geom_point() +
theme(plot.margin = unit(c(1, 3, 1, 1), "lines"))
for (i in 1:length(df$n)) {
p <- p +
annotation_custom(
grob = textGrob(label = df$n[i], hjust = 0, gp = gpar(cex = 1.5)),
ymin = df$y[i],
ymax = df$y[i],
xmin = 14.3,
xmax = 14.3
)
}
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)
```
方法2:
```R
df <- data.frame(y = c("cat1", "cat2", "cat3"), x = c(12, 10, 14), n = c(5, 15, 20))
ggplot(df, aes(x = x, y = y, label = n)) +
geom_point() +
geom_text(x = 14.25, hjust = 0, size = 8) +
coord_cartesian(xlim = c(10, 14), clip = 'off') +
theme(plot.margin = unit(c(1,3, 1, 1), "lines"))
```
方法3:
```R
df <- data.frame(y = c("cat1", "cat2", "cat3"), x = c(12, 10, 14), n = c(5, 15, 20))
ggplot(df, aes(x = x, y = y, label = n)) +
geom_point() +
geom_text(size = 8, hjust = -0.5)
```
以上是三种在ggplot2中添加标签的方法。你可以根据需要选择适合你的情况的方法。
阅读全文