I have a monthly temporal series with sales in this format (so there's no month or year column):
ts(data = Datos, start = c(2015,1), end = c(2020,12), frequency = 12)
How can I plot a multi-boxplot by month?
If you want to use the boxplots to display the variations for a specific month across the given five years period you can try:
library(tidyverse)
library(tsibble)
ts(data = sample(100), start = c(2015,1), end = c(2020,12), frequency = 12) %>%
as_tsibble() %>%
mutate(month = as.factor(month(index))) %>%
ggplot(aes(month, value)) +
geom_boxplot()
Related
I am trying to compare different years' variables but I am having trouble plotting them together.
The time series is a temperature series which can be found in https://github.com/gonzalodqa/timeseries as temp.csv
I would like to plot something like the image but I find it difficult to subset the months between the years and then combine the lines in the same plot under the same months
If someone can give some advice or point me in the right direction I would really appreciate it
You can try this way.
The first chart shows all the available temperatures, the second chart is aggregated by month.
In the first chart, we force the same year so that ggplot will plot them aligned, but we separate the lines by colour.
For the second one, we just use month as x variable and year as colour variable.
Note that:
with scale_x_datetime we can hide the year so that no one can see that we forced the year 2020 to every observation
with scale_x_continous we can show the name of the months instead of the numbers
[just try to run the charts with and without scale_x_... to understand what I'm talking about]
month.abb is a useful default variable for months names.
# read data
df <- readr::read_csv2("https://raw.githubusercontent.com/gonzalodqa/timeseries/main/temp.csv")
# libraries
library(ggplot2)
library(dplyr)
# line chart by datetime
df %>%
# make datetime: force unique year
mutate(datetime = lubridate::make_datetime(2020, month, day, hour, minute, second)) %>%
ggplot() +
geom_line(aes(x = datetime, y = T42, colour = factor(year))) +
scale_x_datetime(breaks = lubridate::make_datetime(2020,1:12), labels = month.abb) +
labs(title = "Temperature by Datetime", colour = "Year")
# line chart by month
df %>%
# average by year-month
group_by(year, month) %>%
summarise(T42 = mean(T42, na.rm = TRUE), .groups = "drop") %>%
ggplot() +
geom_line(aes(x = month, y = T42, colour = factor(year))) +
scale_x_continuous(breaks = 1:12, labels = month.abb, minor_breaks = NULL) +
labs(title = "Average Temperature by Month", colour = "Year")
In case you want your chart to start from July, you can use this code instead:
months_order <- c(7:12,1:6)
# line chart by month
df %>%
# average by year-month
group_by(year, month) %>%
summarise(T42 = mean(T42, na.rm = TRUE), .groups = "drop") %>%
# create new groups starting from each July
group_by(neworder = cumsum(month == 7)) %>%
# keep only complete years
filter(n() == 12) %>%
# give new names to groups
mutate(years = paste(unique(year), collapse = " / ")) %>%
ungroup() %>%
# reorder months
mutate(month = factor(month, levels = months_order, labels = month.abb[months_order], ordered = TRUE)) %>%
# plot
ggplot() +
geom_line(aes(x = month, y = T42, colour = years, group = years)) +
labs(title = "Average Temperature by Month", colour = "Year")
EDIT
To have something similar to the first plot but starting from July, you could use the following code:
# libraries
library(ggplot2)
library(dplyr)
library(lubridate)
# custom months order
months_order <- c(7:12,1:6)
# fake dates for plot
# note: choose 4 to include 29 Feb which exist only in leap years
dates <- make_datetime(c(rep(3,6), rep(4,6)), months_order)
# line chart by datetime
df %>%
# create date time
mutate(datetime = make_datetime(year, month, day, hour, minute, second)) %>%
# filter years of interest
filter(datetime >= make_datetime(2018,7), datetime < make_datetime(2020,7)) %>%
# create increasing group after each july
group_by(year, month) %>%
mutate(dummy = month(datetime) == 7 & datetime == min(datetime)) %>%
ungroup() %>%
mutate(dummy = cumsum(dummy)) %>%
# force unique years and create custom name
group_by(dummy) %>%
mutate(datetime = datetime - years(year - 4) - years(month>=7),
years = paste(unique(year), collapse = " / ")) %>%
ungroup() %>%
# plot
ggplot() +
geom_line(aes(x = datetime, y = T42, colour = years)) +
scale_x_datetime(breaks = dates, labels = month.abb[months_order]) +
labs(title = "Temperature by Datetime", colour = "Year")
To order month differently and sum up the values in couples of years, you've to work a bit with your data before plotting them:
library(dplyr) # work data
library(ggplot2) # plots
library(lubridate) # date
library(readr) # fetch data
# your data
df <- read_csv2("https://raw.githubusercontent.com/gonzalodqa/timeseries/main/temp.csv")
df %>%
mutate(date = make_date(year, month,day)) %>%
# reorder month
group_by(month_2 = factor(as.character(month(date, label = T, locale = Sys.setlocale("LC_TIME", "English"))),
levels = c('Jul','Aug','Sep','Oct','Nov','Dec','Jan','Feb','Mar','Apr','May','Jun')),
# group years as you like
year_2 = ifelse( year(date) %in% (2018:2019), '2018/2019', '2020/2021')) %>%
# you can put whatever aggregation function you need
summarise(val = mean(T42, na.rm = T)) %>%
# plot it!
ggplot(aes(x = month_2, y = val, color = year_2, group = year_2)) +
geom_line() +
ylab('T42') +
xlab('month') +
theme_light()
A slightly different solution without the all dates to 2020 trick.
library(tidyverse)
library(lubridate)
df <- read_csv2("https://raw.githubusercontent.com/gonzalodqa/timeseries/main/temp.csv")
df <- df |>
filter(year %in% c(2018, 2019, 2020)) %>%
mutate(year = factor(year),
month = ifelse(month<10, paste0(0,month), month),
day = paste0(0, day),
month_day = paste0(month, "-", day))
df |> ggplot(aes(x=month_day, y=T42, group=year, col=year)) +
geom_line() +
scale_x_discrete(breaks = c("01-01", "02-01", "03-01", "04-01", "05-01", "06-01", "07-01", "08-01", "09-01", "10-01", "11-01", "12-01"))
I am looking at data from Nov to April and would like to have a plot starting from Nov to April. Below is my sample code to screen out month of interests.
library(tidyverse)
mydata = data.frame(seq(as.Date("2010-01-01"), to=as.Date("2011-12-31"),by="days"), A = runif(730,10,50))
colnames(mydata) = c("Date", "A")
DF = mydata %>%
mutate(Year = year(Date), Month = month(Date), Day = day(Date)) %>%
filter(Month == 11 | Month == 12 | Month == 01 | Month == 02 | Month == 03 | Month == 04)
I tried to re-order the data starting at month 11 followed by month 12 and then month 01,02,03,and,04. I used the code factor(Month, levels = c(11,12,01,02,03,04)) along with the code above but it didn't work.
I wanted a plot that starts at month Nov and ends on April. The following code gave me attached plot
ggplot(data = DF, aes(Month,A))+
geom_bar(stat = "identity")+ facet_wrap(~Year, ncol = 2)
Right now, the plot is starting at January all the way to December- I dont want this. I want the plot starting at November, and all the way to April. I tried to label the plot using scale_x_date(labels = date_format("%b", date_breaks = "month", name = "Month") which didn't work. Any help would
I converted Month to character before applying factor() and it worked.
DF = mydata %>%
mutate(Year = year(Date), Month = month(Date), Day = day(Date)) %>%
filter(Month %in% c(11, 12, 1, 2, 3, 4)) %>%
mutate(Month = sprintf("%02d", Month)) %>%
mutate(Month = factor(Month, levels = c("11","12","01","02","03","04")))
ggplot(data = DF, aes(Month,A))+
geom_bar(stat = "identity")+ facet_wrap(~Year, ncol = 2)
Output:
user2332849 answer is close but does introduce an error. The bar are not in the correct order. For example for 2010, it plot is showing November and December's data prior to the beginning of the year's data. In order to plot in the proper order the year will need adjustment so that the calendar starts on month 11 and goes to month 4.
#Convert month to Factor and set desired order
DF$Month<- factor(DF$Month, levels=c(11, 12, 1, 2, 3, 4))
#Adjust the year to match the year of the beginning of series
#For example assign Jan, Feb, Mar and April to prior year
DF$Year<-ifelse(as.integer(as.character(DF$Month)) <6, DF$Year-1, DF$Year)
#plot
ggplot(data = DF, aes(Month,A))+
geom_bar(stat = "identity") +
facet_wrap(~Year, ncol = 3)
In the plot below the first 4 months of 2010 is shifted to become the last 4 periods of the prior year. And the last 2 months of 2011 is ready for the first 4 months of 2012.
I feel like this should be an easy task for ggplot, tidyverse, lubridate, but I cannot seem to find an elegant solution.
GOAL: Create a bar graph of my data aggregated/summarized/grouped_by year and month.
#Libraries
library(tidyverse)
library(lubridate)
# Data
date <- sample(seq(as_date('2013-06-01'), as_date('2014-5-31'), by="day"), 10000, replace = TRUE)
value <- rnorm(10000)
df <- tibble(date, value)
# Summarise
df2 <- df %>%
mutate(year = year(date), month = month(date)) %>%
unite(year_month,year,month) %>%
group_by(year_month) %>%
summarise(avg = mean(value),
cnt = n())
# Plot
ggplot(df2) +
geom_bar(aes(x=year_month, y = avg), stat = 'identity')
When I create the year_month variable, it naturally becomes a character variable instead of a date variable. I have also tried grouping by year(date), month(date) but then I can't figure out how to use two variables as the x-axis in ggplot. Perhaps this could be solved by flooring the dates to the first day of the month...?
You were really close. The missing pieces are floor_date() and scale_x_date():
library(tidyverse)
library(lubridate)
date <- sample(seq(as_date('2013-06-01'), as_date('2014-5-31'), by = "day"),
10000, replace = TRUE)
value <- rnorm(10000)
df <- tibble(date, value) %>%
group_by(month = floor_date(date, unit = "month")) %>%
summarize(avg = mean(value))
ggplot(df, aes(x = month, y = avg)) +
geom_bar(stat = "identity") +
scale_x_date(NULL, date_labels = "%b %y", breaks = "month")
I have a data frame called "fish" which contains variables such as mass, length and day of the year. I need to make a boxplot of fish length by month but there is no month variable, only day of the year (i.e 1:365). How can I group days by 30 to represent month and then name them so I can make a boxplot? I have attached a screenshot of the data.
You can use this solution:
#load package
require(tidyverse)
#make dataframe
n <- 100
tmp <- tibble(year = rep(c(1994,1994),n/2),day = c(1:n),lenght_mm = rnorm(n),mass_g = rnorm(n,5))
#add month column
tmp <- tmp %>%
mutate(month = as.factor(ifelse(day%%30/30 != 0,day%/%30 +1,day%/%30)))
#make plot
tmp %>%
ggplot(aes(month,lenght_mm,col = month)) +
geom_boxplot() +
theme_bw()
I would add a new column with the full date:
as.Date(104, origin = "2014-01-01")
and from that you can group by month.
months(as.Date(104, origin = "2014-01-01"))
put together:
df %>% mutate(date = as.Date(day_of_the_year, origin = "2014-01-01"),
month = months(date))
I wish to plot the frequency of subscribers over time using start and end date.
I have a method that creates a row for each day per subscriber, then calculates the frequency per day, then plots the frequency by day.
This works fine for small data but does not scale to large subscriber numbers because the rows per customer step is too big.
Is there an efficient method? Many thanks for any help.
library(ggplot2)
library(dplyr)
# create dummy dataset
subscribers <- data.frame(id = seq(1:10),
start = sample(seq(as.Date('2016/01/01'), as.Date('2016/06/01'), by="day"), 10),
end = sample(seq(as.Date('2017/01/01'), as.Date('2017/06/01'), by="day"), 10))
# creates a row for each day per user - OK for small datasets, but not scalable
date_map <- Map(seq, subscribers$start, subscribers$end, by = "day")
date_rows <- data.frame(
org = rep.int(subscribers$id, vapply(date_map, length, 1L)),
date = do.call(c, date_map))
# finds the frequency of users for each day
date_rows %>%
group_by(date) %>%
dplyr::summarise(users = n()) -> plot_data
ggplot(data = plot_data,
aes(x = date, y = users)) +
geom_line(size = 1.2,alpha = .6)
How's this?
library(tidyverse)
df <- subscribers %>%
gather(key, value, start, end) %>%
mutate(key = ifelse(key == "start",1,-1)) %>%
arrange(value)
df$cum <- cumsum(df$key)
ggplot(data = df,
aes(x = value, y = cum)) +
geom_step()