我使用 geom_count 将重叠点可视化为大小组,但我还想将实际计数作为标签添加到绘制的点上,如下所示:
然而,为了实现这一目标,我必须创建一个包含计数的新数据框,并在 geom_text 中使用这些数据,如下所示:
#Creating two data frames
data <- data.frame(x = c(2, 2, 2, 2, 3, 3, 3, 3, 3, 4),
y = c(1, 2, 2, 2, 2, 2, 3, 3, 3, 3),
id = c("a", "b", "b", "b", "c",
"c", "d", "d", "d", "e"))
data2 <- data %>%
group_by(id) %>%
summarise(x = mean(x), y = mean(y), count = n())
# Creating the plot
ggplot(data = data, aes(x = x, y = y)) +
geom_count() +
scale_size_continuous(range = c(10, 15)) +
geom_text(data = data2,
aes(x = x, y = y, label = count),
color = "#ffffff")
Run Code Online (Sandbox Code Playgroud)
有没有办法以更优雅的方式实现这一点(即不需要第二个数据框)?我知道您可以使用 访问 geom_count 中的计数..n..,但如果我尝试访问 中的计数geom_text,这是行不通的。
你期待这个吗:
ggplot(data %>%
group_by(id) %>%
summarise(x = mean(x), y = mean(y), count = n()),
aes(x = x, y = y)) + geom_point(aes(size = count)) +
scale_size_continuous(range = c(10, 15)) +
geom_text(aes(label = count),
color = "#ffffff")
Run Code Online (Sandbox Code Playgroud)
更新:
如果必须使用geom_count,则可以使用以下方法实现预期输出:
p <- ggplot(data = data, aes(x = x, y = y)) +
geom_count() + scale_size_continuous(range = c(10, 15))
p + geom_text(data = ggplot_build(p)$data[[1]],
aes(x, y, label = n), color = "#ffffff")
Run Code Online (Sandbox Code Playgroud)