user3585829
user3585829

Reputation: 965

hide missing dates from x-axis ggplot2

I am trying to make a chart in ggplot2 (barplot). There are several days in between data points in my data set. I'd like to only graph the dates where variables are and omit the empty dates.

I have been searching for an hour trying to find an answer to this. I found some replies here indicating that the fix is this:

scale_x_date(format = '%d%b', major='days')

However, those arguments inside of scale_x_date don't seem to work anymore. Does anyone have a quick and easy solution?

Upvotes: 3

Views: 3981

Answers (1)

tegancp
tegancp

Reputation: 1202

I would be remiss if I didn't mention the ggplot2 docs which are a fantastic resource, packed full of well-documented examples. They are often the best place to start when you don't know how to do something with ggplot.

The "translation" for the code you quoted above in the current framework is:

scale_x_date(breaks='days', labels=date_format("%d%b"))

which will require the package scales. Unless you have fairly few dates, you probably also would want an adjustment like

theme(axis.text.x = element_text(angle=45))

If you only want to label the dates for which you have data, try

scale_x_date(breaks=df$date, labels = date_format("%m/%d"))

where df$date is the column of your dataframe containing the dates, and of course you can use your preferred date format string.

Upvotes: 1

Related Questions