23

does anyone know how to rotate axis ticks in the date format with ggplot2? I want to get labels with "Date-Month" (ex. "1985-5") with a 45° angle on the x axis.

data sample:

Station Date Ptot
A 1980-02 16
A 1980-03 19
A 1980-04 40
A 1980-05 48
A 1980-06 NA
A 1980-07 18.5
A 1980-08 24.6
B 1980-07 50.8
B 1980-08 28.9
B 1980-09 32.9
B 1980-10 47.9
B 1980-11 16.3

I tried this:

library(ggplot2)
library(scales)

plot <- ggplot(data=na.omit(data), aes(x=Date, y=Ptot, group=Station))+
   geom_line()+
   facet_grid(Station~.)+
   scale_x_date(breaks = "year", labels=date_format("%Y-%m"))+
   xlab("Year")+
   ylab("Prec (mm)")+
   labs(colour = "Station")+
   theme(axis.text.x = element_text(angle = 45, hjust = 1))+
   theme_bw()

plot

but it doesn't work.

Thanks!

3
  • 1
    you'll have to provide a better reproducible example than that with data, and your complete code. Commented Apr 5, 2013 at 16:12
  • OK, I just improved details in the question... Commented Apr 5, 2013 at 16:30
  • Check @Didzis' edit where he explains the problem with your Date column. Commented Apr 5, 2013 at 16:44

1 Answer 1

54

First, you should make column Date as date. As it do not have the day provided, you should add for example 01 to each date and convert them.

data$Date<-as.Date(paste(data$Date,"-01",sep=""),format="%Y-%m-%d")

To get correct placement of labels under x axis you should set not just angle= but also hjust=1 to ensure that end of the label is placed under the tick mark. Also theme_bw() should be placed before theme specification of axis texts.

ggplot(data=na.omit(data), aes(x=Date, y=Ptot, group=Station))+
  geom_line()+
  facet_grid(Station~.)+
  scale_x_date(breaks = "month", labels=date_format("%Y-%m"))+
  xlab("Year")+
  ylab("Prec (mm)")+theme_bw()+
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

I was just about to write that.
Thanks! I din't mention that I had done the date transformation of my "Date" column... I still have to learn to optimize the use of this forum. My problem was the position of theme_bw()
@user2165907 theme_bw() also set parameters for the axis.text, so it should be placed before your parameters.
UPDATE you now might need to add vjust = 0.5 to get better alignment. Thanks to @jupp0r's comments in this answer theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.