简体   繁体   中英

stat_count for month-year combination

I want to plot the number of occurrences of a certain date in a data frame. I write the following:

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) +
  stat_count(aes(x = (dates)))

在此处输入图像描述

Basically the code plots the number of occurences of each day-month-year combination in a date. Now, I want to create a plot that counts the number of occurences of each month-year combination in a date. Basically, considering the picture, bars that have the same month-year should be one above the other. Does anyone have any idea?

library(tidyverse)
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) 

data <- mutate(data,
               dates = lubridate::as_date(dates),
               year_month=paste(lubridate::year(dates),
                                str_pad(lubridate::month(dates), width = 2, pad = 0),
                                sep="-"))

ggplot(data) +
  stat_count(aes(x = year_month))

在此处输入图像描述

If you want the days to be distinguishable (not sure how useful this might be with a real world example) you can use fill , notice factor(dates) so that dates is treated as a factor.

ggplot(data) +
  stat_count(aes(x = year_month, fill=factor(dates)))

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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