【问题标题】:Is there a way to add legend and count to each level for geom_point?有没有办法为 geom_point 添加图例和计数到每个级别?
【发布时间】:2023-01-13 11:15:07
【问题描述】:

有没有办法添加带有计数的图例以给出每行的密度?

或者更简单的方式来展示它?

非常感谢!

甚至无法添加图例 :)

我使用的代码:

data %>% 
  ggplot(aes(x = subscribed, y = campaign)) +
  geom_point () +
  geom_jitter() 

【问题讨论】:

    标签: r ggplot2 count legend


    【解决方案1】:

    您可以为每个组(已订阅)创建一个 label,它是预先计算的 n() 观察值的数量,并将它们分配为列字符串。这可以在 aes 中使用,以确保它显示在图例中。这是一个可重现的例子:

    library(dplyr)
    library(ggplot2)
    df %>%
      group_by(subscribed) %>%
      mutate(count = paste0(subscribed, ' (n = ', n(), ')')) %>%
      ggplot(aes(subscribed, campaign, colour = factor(count))) + 
      geom_jitter()
    

    创建于 2023-01-12 reprex v2.0.2


    创建数据:

    df <- data.frame(campaign = runif(100),
                     subscribed = rep(c("no", "yes"), 50))
    

    【讨论】:

    • 完美的工作,谢谢!
    【解决方案2】:

    我找到了另一种方法来以更清晰的方式显示与此类似的数据。

    但是,我无法弄清楚传说大声笑

    我使用的代码是:

     p <- ggplot(data = data, aes(x = subscribed, y = pdays)) +
      geom_count() + scale_size_continuous(range = c(7, 30))
    
    p + geom_text(data = ggplot_build(p)$data[[1]], 
                  aes(x, y, label = n), color = "#ffffff") +
      scale_y_continuous(breaks = seq(0, 30, by = 4))
    

    【讨论】:

      猜你喜欢
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 2020-05-06
      • 2020-07-05
      • 1970-01-01
      • 2022-08-11
      相关资源
      最近更新 更多