Can 'date' scale use end-of-month as tick label ?

131 views
Skip to first unread message

Mauricio

unread,
Mar 21, 2011, 3:50:25 PM3/21/11
to ggplot2
Hi,

It seems to me that when plotting dates (say on the x axis), ggplot2
uses tick mark labels that correspond the first of the month. Can
this be changed so that the end-of-month is the date that corresponds
to the tick?

Thanks,
Mauricio

Brian Diggs

unread,
Mar 21, 2011, 7:37:06 PM3/21/11
to ggplot2
Not that I could tell using scale_x_datetime. However, you can fake
it using scale_x_continuous.

library("ggplot2")

n <- 100
DF <- data.frame(Day = seq(as.Date("2010-01-01"), by="day",
length.out=n),
value=(1:n)+rnorm(n))
end.of.month <- seq(min(DF$Day), max(DF$Day), by="month") - 1

ggplot(DF, aes(x=as.numeric(Day), y=value)) +
geom_point() +
scale_x_continuous(breaks=as.numeric(end.of.month),
labels=as.character(end.of.month))

> Thanks,
> Mauricio

--
Brian S. Diggs, PhD
Senior Research Associate, Department of Surgery
Oregon Health & Science University

Mauricio

unread,
Mar 21, 2011, 8:28:34 PM3/21/11
to ggplot2
Brian, thanks for the suggestion.

I did notice a negative side effect. In the 'before' case, ggplot
displays my date labels in 'mmm-yy' format, which is nice and clean.
Using the 'fake out' method, ggplot displays the labels in 'yyyy-mm-
dd' format, which can be quite clunky.

Perhaps an alternative would be to simply subtract one month from all
the data to be plotted.

-Mauricio

Brian Diggs

unread,
Mar 22, 2011, 1:54:47 PM3/22/11
to Mauricio, ggplot2
On 3/21/2011 5:28 PM, Mauricio wrote:
> Brian, thanks for the suggestion.
>
> I did notice a negative side effect. In the 'before' case, ggplot
> displays my date labels in 'mmm-yy' format, which is nice and clean.
> Using the 'fake out' method, ggplot displays the labels in 'yyyy-mm-
> dd' format, which can be quite clunky.

You can control exactly what is displayed in the
labels=as.character(end.of.month) call. Just change it to
labels=format(end.of.month, "%b-%y")

I had left it in yyyy-mm-dd format because I thought end of month was
non-standard and needed the full day expressed. (Otherwise the first of
the month would be assumed).

> Perhaps an alternative would be to simply subtract one month from all
> the data to be plotted.

That could work, but I would think it would be misleading. But if it is
convention in your field, then that is fine.

> -Mauricio

Mauricio

unread,
Mar 23, 2011, 10:51:35 AM3/23/11
to ggplot2
Brian,

Your suggestion to use scale_x_continuous got me very close to what
was needed. The labels corresponding to every monthly break are too
close together and overprinting. I didn't see any examples on the
documentation of scale_x_continuous on how to control the interval
between labels ... say every 2 breaks (i.e. "2 month"). All the
examples show labels for all breaks.

Might you have any insight into this?

Thanks for all your help.

-Mauricio
Reply all
Reply to author
Forward
0 new messages