ggplot: display all weeks on the x-axis and add different labels

In the following plot, how do I display all the weeks on the x axis? In addition, how can I display week_other instead of week?

library(tidyverse)
library(tsibble)
library(lubridate)

# Toy Data-------------

set.seed(123)
date <- seq(ymd("20200101"), ymd("20220430"), by = "1 day")
df <- tibble(date = date) %>% 
  mutate(week = yearweek(date)) %>% 
  distinct(week) %>% 
  # represent week in different format
  mutate(week_other = str_trim(as.character(week)),
         week_other = str_replace(week_other, "W", "0"),
         week_other = str_replace(week_other, " ", ""),
         week_other = as.numeric(week_other)) %>% 
  # generate toy variable
  mutate(profit = row_number()*5 + rnorm(122, 100, 100))

# Plot-----------
df %>% 
  ggplot(aes(x = week, y = profit)) +
  geom_line()

Created on 2022-05-09 by the reprex package (v2.0.0)

Here's how you can display all the weeks on x axis.

df %>% 
  ggplot(aes(x = as.Date(week), y = profit)) +
  geom_line() +
  scale_x_date(date_breaks = "1 week", # could be 2 weeks or 1 month or anything
               labels = scales::date_format(format = "W%W-%y")) +
  # rotate labels for visibility
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

The format "W%W-%y" means format like "W12-19".

To display week_other, use the following codes. You need to provide group=1 as explained here.

df %>% 
  ggplot(aes(x = factor(week_other), y = profit)) +
  geom_line(aes(group = 1)) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

This is my first answer so I can't paste the output here but these work. :face_with_peeking_eye:

1 Like

@harsh17 Many thanks! How can I achieve breaks in the second scenario, i.e., week_other? That is, rather than showing all the weeks, how can I display, for example, every fourth week?

I feel like you are approaching the problem more complicated than it is. You don't need to wrangle with `week_other'. Here's an approach where I changed the output format of the date on the x axis.

df %>% 
  ggplot(aes(x = as.Date(week), y = profit)) +
  geom_line() +
  scale_x_date(date_breaks = "4 weeks", # could be 2 weeks or 1 month or anything
               labels = scales::date_format(format = "%Y0%W")) +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.