In-class Exercise 6 - Horizon Plot

Author

Li Jiayi

Published

February 24, 2024

Modified

February 24, 2024

Load Package

Load the ggHoriPlot package

pacman::p_load(ggHoriPlot, ggthemes, tidyverse)

Import Data

the csv has already been changed to long format using excel. To convert in R, can use pivot_longer function instead

averp <- read_csv("data/AVERP.csv")

Data Preperatin

Date column is imported as a character field, and it should be converted into a date format instead.

 averp <- averp %>% mutate(`Date` = dmy(`Date`))

another way is to use lubridate

Plotting

The code chunk below use geom_horizon to create a Horizon Plot, facet_grid here creates the plot for different Consumer Items

theme_few() : use as less number of features possible

scale_fill_hcl(palette = 'RdBu' : here creates a diverging color using color palette, only if there is decrease/increase

Show the code
averp %>% 
  filter(Date >= "2018-01-01") %>%
  ggplot() +
  geom_horizon(aes(x = Date, y=Values), 
               origin = "midpoint", 
               horizonscale = 6)+
  facet_grid(`Consumer Items`~.) +
    theme_few() + 
  scale_fill_hcl(palette = 'RdBu') + 
  theme(panel.spacing.y=unit(0, "lines"), strip.text.y = element_text(
    size = 5, angle = 0, hjust = 0),
    legend.position = 'none',
    axis.text.y = element_blank(),
    axis.text.x = element_text(size=7),
    axis.title.y = element_blank(),
    axis.title.x = element_blank(),
    axis.ticks.y = element_blank(),
    panel.border = element_blank()
    ) +
    scale_x_date(expand=c(0,0), date_breaks = "3 month", date_labels = "%b%y") +
  ggtitle('Average Retail Prices of Selected Consumer Items (Jan 2018 to Dec 2022)')