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.
library(data.table) library(lubridate) library(ggplot2) 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']
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, color='#000000', angle=45, 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 :-).