【问题标题】:Count dates that have a certain day per month and year计算每月和每年有特定日期的日期
【发布时间】:2020-12-02 21:37:39
【问题描述】:

我想绘制具有特定日期的日期,以便分别计算具有相同日期的不同日期。例如,我写如下:

dates <-  c("2018-01-03", "2018-01-17", "2018-02-03", "2018-02-03", "2018-02-16", 
            "2018-02-26", "2018-03-03")
data <- as.data.frame(dates)

ggplot(data) +
  geom_bar(aes(x = day(dates)), 
           stat = "count")

但是,这给了我 4 天 3、1 天 16、1 天 17 和 1 天 26(见图)。但是,我想要得到的是: 2018-01:1 天 3 和 1 天 17 2018-02:2 天 3、1 天 16 和 1 天 26 2018-03:1 天 3

我不知道我是否足够清楚

【问题讨论】:

  • 您在这里使用了不正确的函数,即 day(),这就是为什么它在 x 轴上按天显示的原因
  • 是的,这就是重点。是否有另一种方式(功能)来实现我想要的?
  • 看解决办法,或许我理解正确

标签: r ggplot2


【解决方案1】:

您可以使用table 生成您要查找的条形图:

as.data.frame(table(dates)) %>% 
    ggplot() + geom_bar(aes(x=dates, y=Freq), stat="identity")

或者,更清洁一点:

as.data.frame(table(dates)) %>% 
    ggplot() + geom_bar(aes(x=dates, y=Freq, fill=month(dates)), stat="identity")

【讨论】:

  • 我认为解决方案实际上是使用 stat_count ggplot(data) + stat_count(aes(x = (birthday)))
【解决方案2】:

或者您可能正在寻找这个? (我不确定)

data %>%mutate(dates = as.Date(dates)) %>% group_by(dates) %>% summarise(Freq = n()) %>%
  ggplot() + geom_col(aes(x=dates, y=Freq, fill = Freq)) +
  scale_x_date(date_labels = "%m-%d")

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 2017-02-23
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    相关资源
    最近更新 更多