3

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?

Bacteria
  • 8,406
  • 10
  • 50
  • 67
user3585829
  • 945
  • 11
  • 24
  • 2
    It would be helpful if you also post the call to `ggplot2()` which you are making so that we may reproduce it. – Tim Biegeleisen Jun 17 '15 at 01:32
  • 1
    A small sample of data would be helpful to make sure we are answering the right question. – tegancp Jun 17 '15 at 01:55
  • 1
    See [how to make a great reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – MrFlick Jun 17 '15 at 01:57

1 Answers1

1

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.

tegancp
  • 1,204
  • 6
  • 13
  • Thank you. The final code worked to get rid of the dates where there is no data, but it still leaves this open gap. I was trying to only have the dates where there is data, no gaps. Is there a way to move the bars together and eliminate the open space? – user3585829 Jun 17 '15 at 14:17
  • If the valid dates are evenly spaced, ggplot should do this for you. If they are not evenly spaced, but you want them to be displayed with the same gap between subsequent values, then you need to tell ggplot to ignore the fact that these are dates, just treat them as labels of an ordered set. You can accomplish this with `df$date <- factor(df$date)`. – tegancp Jun 17 '15 at 16:00
  • Looks like the link to the ggplot docs does not work anymore @tegancp – ok1more Oct 13 '22 at 13:51
  • @ok1more thanks, I updated to a current link to the docs – tegancp Oct 13 '22 at 19:56