Keep only a few x-axis labels for a qualitative variable

63 Views Asked by At

I am trying to plot a data.table with two columns : a Date column, and another quantitative variable. My quantitative variable has seasonal variations, but is not exactly the same throughout the years. My goal is to compare the evolution of this variable across different years.

Here is a dummy dataset :

library(tidyverse)

data=data.table(date=seq(as.Date('1999/01/01'), as.Date('2001/01/01'), by="day"),
                value=rep(seq(0.1, 36.6,0.1)),2)

I want to facet this ggplot by year. For that, I use strftime :

ggplot + 
   aes(x = strftime(Date,"%m-%d"), y=value,group="") +
   facet_wrap(~strftime(Date,"%Y"),,nrow=3) + 
   geom_line()

This works perfectly, but gives an ugly background and an unreadable x axis legend, since we have one legend + one graduation per day.

The ugly graph

I figured the graph would be more readable if I could keep only one legend label per month. Do someone know how to do that ?

Edit

After @Gregor Thomas's edit and comment, I would like to stress that keeping the date format for the x axis and changing the axis format using scale_x_date(date_breaks = "6 month") (like said here) gives an plot that can not be interpreted :

The useless graph

It is worse in my real dataset, since I have more than two years. The goal of strftime was to adress this problem.

Edit 2 : a solution

I found a solution for this, using scale_x_discrete :

end_month=c(
  "01-31",
  "02-28",
  "03-31",
  "04-30",
  "05-31",
  "06-30",
  "07-31",
  "08-31",
  "09-30",
  "10-31",
  "11-30",
  "12-31"
)

ggplot + 
   aes(x = strftime(date,"%m-%d"), y=value,group="") +
   facet_wrap(~strftime(date,"%Y"),,nrow=3) + 
   geom_line() +
   scale_x_discrete(break=end_month)

This answers the question. However, I would be interested in another solution especially if I it is possible to keep the Date format
for the x axis while still keeping the facet aligned. The reason for that is that I have breaks in my time series and the strftime gives the impression that I have a continuous series.

0

There are 0 best solutions below