Add count as label to points in geom_count

随声附和 提交于 2019-12-13 00:36:51

问题


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:

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

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.


回答1:


Are you expecting this:

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

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



来源:https://stackoverflow.com/questions/46851450/add-count-as-label-to-points-in-geom-count

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!