0

I am having trouble figuring out how to label the x axis to correspond to points. X represent 4 dates and I would like the month-day (e.g., 'Aug 27') format to appear as x labels.

Thanks in advance for any help!

Code:

ggplot(day28.long,aes(x=day,y=movement))+
 geom_point(aes(colour=Horse))+
  geom_line(aes(colour=Horse))

The structure of the data is:

str(day28.long)
'data.frame':   60 obs. of  3 variables:
 $ day     : Date, format: "2016-08-27" "2016-09-24" "2016-10-22" "2016-11-19" ...
 $ Horse   : chr  "42012" "42012" "42012" "42012" ...
 $ movement: int  418 291 255 123 314 270 271 141 444 471 ...

Plot where x labels aren't matched to points

Karolis Koncevičius
  • 9,417
  • 9
  • 56
  • 89
  • 2
    Your plot already appears to have the `Mon-Day` format. What is it you are looking to change? Also, please read [here](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on how to provide a reproducible example. In the mean time, look into `scale_x_date` and if that doesn't work for what you want, explain why. – Mark Peterson Feb 03 '17 at 21:36

1 Answers1

2

By default, ggplot2 uses scale_x_date() or scale_y_date(), resp., for class Date axes. Tick marks and grid lines are placed at "nice" dates, e.g., 1st and 15th of a month. Scaling doesn't care about specific dates in the data.

However, scale_*_date() has two parameters which allow to customize breaks and labels.

ggplot(day28.long,aes(x=day, y=movement, colour=Horse, group = Horse)) +
  geom_point() +
  geom_line() +
  scale_x_date(breaks = unique(day28.long$day),
               date_labels = "%b %d"
  )

enter image description here

The breaks are taken from the day column.

By default, labels would appear in the YYYY-mm-dd format. Therefore, the parameter date_labels = "%b %d" tells ggplot2 how to display the dates on the axis.

Note that %b is the Abbreviated month name in the current locale on this platform (see ?strptime). This is why Okt 22 is printed in the chart instead of Oct 22.

Data

Unfortunately, the OP hasn't provided the data for a reproducible example. So, I had to make some sample data.

day28.long <- data.frame(
  day = as.Date(rep(c("2016-08-27", "2016-09-24", "2016-10-22", "2016-11-19"), 2)),
  Horse = rep(c("42012", "42013"), each = 4),
  movement = as.integer(c(418, 291, 255, 123, 314, 270, 271, 141)),
  stringsAsFactors = FALSE)

str(day28.long)
#'data.frame':  8 obs. of  3 variables:
# $ day     : Date, format: "2016-08-27" "2016-09-24" "2016-10-22" ...
# $ Horse   : chr  "42012" "42012" "42012" "42012" ...
# $ movement: int  418 291 255 123 314 270 271 141
Uwe
  • 41,420
  • 11
  • 90
  • 134
  • Any idea how to use a different locale other than temporarily setting one with `Sys.setlocale()`? – cbrnr Oct 23 '20 at 10:28