简体   繁体   English

您可以为ggplot中每个因子级别的图例添加计数吗?

[英]Can you add a count to the legend for each level of a factor in ggplot?

I am producing a scatterplot using ggplot, and will be colouring the data points by a given factor.我正在使用 ggplot 生成散点图,并将按给定因子对数据点进行着色。 The legend that is produced, details the colour assigned to each level of the factor, but is it possible for it to also count the number of points in each factor.生成的图例详细说明了分配给因子每个级别的颜色,但它是否也可以计算每个因子中的点数。

For example, I have included the code for the cars data set:例如,我已经包含了汽车数据集的代码:

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point(aes(colour = factor(cyl)))

In this plot, I would be looking to have the count for each number of cylinders.在这个 plot 中,我希望得到每个气缸数的计数。 So 4(Count 1), 6(Count 2) and 8(Count 3).所以 4(计数 1)、6(计数 2)和 8(计数 3)。

Thanks in advance.提前致谢。

you can try something like this你可以试试这样的

mtcars %>%
  group_by(cyl) %>%
  mutate(label = paste0(cyl, ' (Count ', n(), ')'))  %>%
  ggplot(aes(wt, mpg)) + 
    geom_point(aes(colour = factor(label)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM