0

I am trying to adjust the way ggplot labels the axis. My code is:

x = as.POSIXct(c(1, 9999999), origin="1970-01-01 00:00:00 CET")
y = c(1,2)
df = data.frame(x=x, y=y)
ggplot()+
geom_line(data = df, aes(y=y, x=x))

and it produces this output: enter image description here

I think it would be intuitive to place the labels mid-month, get rid of mid-month grid lines and so on... a bit like this: enter image description here

Can this be accomplished with ggplot2?

PascalIv
  • 595
  • 7
  • 21
  • you can set the date_breaks and the date_labels in scale_x_datetime – Richard Telford Jun 19 '18 at 12:28
  • Thank you, I was able to get rid of the grid lines I don't want with scale_x_datetime(date_minor_breaks = "1 month", date_labels = "%b") But how do I move the labels to the middle and get clearer seperation lines between the month? I do not want a grid line where I put my labels... – PascalIv Jun 19 '18 at 12:59

1 Answers1

1

This is a very hacky solution, but it's an option. I don't think it's possible to label on minor breaks only, so to do what you're looking for, you need to label on major breaks, offset labels with spaces (or maybe tabs), and then hide the minor break panel lines, like so:

ggplot()+
  geom_line(data = df, aes(y=y, x=x)) +
  scale_x_datetime(date_breaks = "1 month", date_labels=paste0("                                                     ","%b")) +
  theme(panel.grid.minor = element_blank())

enter image description here

phalteman
  • 3,442
  • 1
  • 29
  • 46
  • Thank you, this worked for me. Do you also happen to know if there is a way to adjust the length of the seperation lines between the month? – PascalIv Jun 20 '18 at 06:08
  • @PascalIv, you can change the length of all axis ticks with `theme(axis.ticks.length = unit(2,"mm"))`, substituting the length and units you want inside `unit()`. However, that will change both x and y tick marks, which you can't separate, to my knowledge. If you want just the x axis marks to be longer, then you will need to use custom grobs. There are four good solutions here which you could adapt based on your needs: https://stackoverflow.com/questions/29824773/annotate-ggplot-with-an-extra-tick-and-label – phalteman Jun 20 '18 at 17:32