Dambo
Dambo

Reputation: 3486

How to include minor breaks in ggplot2

I would like to include minor brakes in my chart such that the full date is printed at the beginning of every month, and days are marked just by a tick on the x axis. What I have right now does not retrieve errors but the output is not what I want, since there are no ticks for the days.

library(ggplot2)

df <- data.frame(date=as.Date(1:60,origin = "1970-01-01"),value=rnorm(60,4,3))
str(df)
ggplot()+
  geom_line(data=df, aes(x=date, y=value))+
  scale_x_date(date_breaks = 'month', date_minor_breaks = 'day')

session:

other attached packages:
[1] scales_0.4.0  cowplot_0.6.2 ggplot2_2.1.0 dplyr_0.5.0   zoo_1.7-13  

This issue has been discussed in Formatting dates with scale_x_date in ggplot2 but I wonder if something changed in the meanwhile since if I follow the code that was suggested

scale_x_date(breaks = "1 month", minor_breaks = "1 week", labels=date_format("%B")) 

I actually get an error

> ggplot()+
+   geom_line(data=df, aes(x=date, y=value))+
+   scale_x_date(breaks = "1 month", minor_breaks = "1 week", labels=date_format("%B"))
Error in strsplit(unitspec, " ") : non-character argument

Upvotes: 2

Views: 4819

Answers (1)

shayaa
shayaa

Reputation: 2797

I am not sure what your error is, because this isn't a reproducible sample.

The following code works on my computer and gives you weekly ticks.

ggplot() +
     geom_line(data=df, aes(x=date, y=value)) +
     scale_x_date(date_breaks = "1 week", 
                   date_minor_breaks = "1 day",)

You can change the formatting of the weekly label by using the date_labels argument, e.g., using %D gives you m/d/y, as follows.

ggplot() +
     geom_line(data=df, aes(x=date, y=value)) +
     scale_x_date(date_breaks = "1 week", 
                    date_minor_breaks = "1 day",
                    date_labels = "%D")

and you can change the aesthetic of the ticks by using the theme layer. For example, changing to the following will give you longer or bigger ticks.

   ggplot() +
     geom_line(data=df, aes(x=date, y=value)) +
     scale_x_date(date_breaks = "1 week", 
                   date_minor_breaks = "1 day",) +
    theme(axis.text.x=element_text(size=10),
          axis.ticks = element_line(size = .5),
          axis.ticks.length = unit(.2, "cm"))

Edited: Following your comment, I think this is what you want. Not sure why but it looks a little "ugly" to me. Hope this helps.

library(lubridate) 
not_first_of_the_month<- which(duplicated(floor_date(df$date, "month")))
xlabels <- as.character(df$date)
xlabels[not_first_of_the_month] <-rep("", length(not_first_of_the_month))

ggplot() +
     geom_line(data=df, aes(x=date, y=value)) +
               scale_x_date(breaks = df$date,
                            labels = xlabels,
               date_minor_breaks = "1 day")

Upvotes: 3

Related Questions