将计数作为标签添加到geom_count中的点 [英] Add count as label to points in geom_count

查看:472
本文介绍了将计数作为标签添加到geom_count中的点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用geom_count将重叠的点可视化为大小分组,但是我还想将实际计数作为标签添加到绘制的点,如下所示:

I used geom_count to visualise overlaying points as sized groups, but I also want to add the actual count as a label to the plotted points, like this:

但是,要实现这一点,我必须创建一个包含计数的新数据框,并在geom_text中使用这些数据,如下所示:

However, to achieve this, I had to create a new data frame containing the counts and use these data in geom_text as shown here:

#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")

是否有任何方法可以更优雅地实现此目的(即不需要第二个数据帧)?我知道您可以使用..n..访问geom_count中的计数,但是如果我尝试在geom_text中访问此计数,则无法正常工作.

Is there any way to achieve this in a more elegant way (i.e. without the need for the second data frame)? I know that you can access the count in geom_count using ..n.., yet if I try to access this in geom_text, this is not working.

推荐答案

您是否期望这样:

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")

更新: 如果必须使用geom_count,则可以使用以下命令实现预期的输出:

update: If the usage of geom_count is must, then the expected output can be achieved using:

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")

这篇关于将计数作为标签添加到geom_count中的点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆