Skip to content
Home ยป Displaying weekdays in R’s ggplot2

Displaying weekdays in R’s ggplot2

In the past couple of years, I have been messing around to get weekdays in my ggplot2 charts. However, I discovered a pretty straightforward method to do it properly. All those hours wasted, but no more.

I will demonstrate with an example.

I use data.table for wrangling, and lubridate for proper date notation. Ofcourse, I load in ggplot2. Next, let’s create a sample data set. I downloaded the latest data from the Datastro sunspot observations page.


dt <- fread('daily-sunspot-number.csv')

# Column 1 and 6 only
dt <- dt[,c(1,6)] 
colnames(dt) <- c('DATE','NR')

# Turn date characters in real dates
dt[,DATE := ymd(DATE)]

# Select only April 2018
dt <- dt[DATE <= '2018-04-30' & DATE >= '2018-04-01']

When you’re interested in the weekday, it can be somewhat tricky, throughout your analysis. There’s lubridate and chron that can help out, but even ggplot2 allows tinkering through scale_x_date.

Simply by using the date_labels parameter, one can specify a date format. I used the %a parameter, which gives you an abbreviated weekday. But you can also use the uppercase %A parameter, which will give you the full weekday.

ggplot(dt, aes(x = DATE, y = NR)) + 
  geom_bar(stat = 'identity', fill = 'red') +
  scale_x_date(date_breaks = '1 day', 
               date_labels = '%a | %b %d') +
  theme(axis.text.x = element_text(size=11,
                                   hjust=1)) +
  xlab('') + ylab('')

This will produce the following chart.

As you can see, the days are in my local language, you can change this to English with a couple of lines of code. If you have complete administrator access over your computer, you can (temporarily) change the locale of your computer. Check all the possible locale’s here.

Sys.setlocale("LC_TIME","English United States")

If you run into the error “OS reports request to set locale to “English United States” cannot be honored”, I currently have no straightforward solution for you :-).

By the way, if you’re having trouble understanding some of the code and concepts, I can highly recommend “An Introduction to Statistical Learning: with Applications in R”, which is the must-have data science bible. If you simply need an introduction into R, and less into the Data Science part, I can absolutely recommend this book by Richard Cotton. Hope it helps!

Say thanks, ask questions or give feedback

Technologies get updated, syntax changes and honestly… I make mistakes too. If something is incorrect, incomplete or doesn’t work, let me know in the comments below and help thousands of visitors.

1 thought on “Displaying weekdays in R’s ggplot2”

Leave a Reply

Your email address will not be published. Required fields are marked *