简体   繁体   English

ggplot2 中离散变量的累积计数

[英]Culmulative count of discrete variable in ggplot2

This is related to Plotting cumulative counts in ggplot2 , but that question was dealing with a continuous variable (rather than discrete).这与在 ggplot2 中绘制累积计数有关,但该问题处理的是连续变量(而不是离散变量)。

Here, I have a bar chart在这里,我有一个条形图

set.seed(2021)
dat <- data.frame(x = c(rpois(100, 1), 7, 10))
ggplot(dat) + geom_bar(aes(x, ..count..))

在此处输入图像描述

I'm trying to plot a cumulative count with我正在尝试 plot 累积计数

ggplot(dat) + geom_bar(aes(x, cumsum(..count..)))

在此处输入图像描述

There are gaps when there are 'missing values' (ie when x is 5, 6, 7, 9).当存在“缺失值”时(即当x为 5、6、7、9 时)存在间隙。

Is there a quick and easy way to have a bar chart with gaps filled with bars , ie I will have 11 bars?有没有一种快速简便的方法来制作一个带有条形空白的条形图,即我将有 11 个条形? I could have manually created a data frame with the cumulative counts and plot it as usual, but I'm curious if there's a more elegant way.我可以像往常一样手动创建一个包含累积计数和 plot 的数据框,但我很好奇是否有更优雅的方法。

You can convert the variable to a factor when plotting.您可以在绘图时将变量转换为因子。

ggplot(dat) + geom_bar(aes(factor(x), cumsum(..count..)))

I would not call this an "easy" approach but the only one I could come up with so solve your question:我不会称这是一种“简单”的方法,但我唯一能想到的方法就是解决你的问题:

  1. Pre-summarise your dataset using eg dplyr::count使用例如dplyr::count预先汇总您的数据集

  2. Fill up your dataset with the missing categories using eg tidyr::complete (To this end I first convert x to a factor).使用例如tidyr::complete用缺失的类别填充您的数据集(为此,我首先将x转换为因子)。

  3. Plot via geom_col Plot 通过geom_col

library(ggplot2)
library(dplyr)
library(tidyr)

set.seed(2021)
dat <- data.frame(x = c(rpois(100, 1), 7, 10))
dat <- dat %>% 
  count(x) %>% 
  mutate(x = factor(x, levels = seq(range(x)[1], range(x)[2], by = 1))) %>% 
  tidyr::complete(x, fill = list(n = 0))

ggplot(dat) + geom_col(aes(x, cumsum(n)))

If you'll use stat_bin instead of geom_bar may be that can help..如果您使用stat_bin而不是geom_bar可能会有所帮助..

ggplot(dat) + stat_bin(aes(x, cumsum(..count..)))

在此处输入图像描述

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

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