Breaks for scale_x_date in ggplot2 and R

I am drawing a date value in ggplot2 (in R). I have the following code. As you can see, ggplot2 adds more x-axis breaks that I have in my data. I just want to have an x-tag every time I have a data point in my data frame. How to make ggplot2 just show breaks only with my.dates? There seems to be no breaks argument for scale_x_date

require(ggplot2) my.dates = as.Date(c("2011-07-22","2011-07-23", "2011-07-24","2011-07-28","2011-07-29")) my.vals = c(5,6,8,7,3) my.data <- data.frame(date =my.dates, vals = my.vals) plot(my.dates, my.vals) p <- ggplot(data = my.data, aes(date,vals))+ geom_line(size = 1.5) p <- p + scale_x_date(format="%m/%d", ' ') p 

enter image description here

+9
r ggplot2
Jul 10 '11 at 2:00
source share
1 answer

One approach would be to treat the x axis as numeric and set the aesthetics of gaps and labels using scale_x_continuous() .

 ggplot(my.data, aes(as.numeric(date), vals)) + geom_line(size = 1.5) + scale_x_continuous(breaks = as.numeric(my.data$date) , labels = format(my.data$date, format = "%m/%d")) 

although the gap between 7/24 to 7/28 looks a bit odd in my opinion. However, I think you want to? Let me know if I misinterpreted.

EDIT

As noted above, I was not enthusiastic about how the breaks looked, especially with a gray grid in the background. Here is one way to preserve a rectangular grid and only indicate the points where we have data. You can do it all in a ggplot call, but it seems to me that making processing outside of ggplot is easier. First, create a vector that contains a sequence of numbers corresponding to dates. Then we will update the corresponding labels and replace the NA " " entries so that something does not appear on the x axis for these entries:

 xscale <- data.frame(breaks = seq(min(as.numeric(my.data$date)), max(as.numeric(my.data$date))) , labels = NA) xscale$labels[xscale$breaks %in% as.numeric(my.data$date)] <- format(my.data$date, format = "%m/%d") xscale$labels[is.na(xscale$labels)] <- " " 

This gives us something similar:

  breaks labels 1 15177 07/22 2 15178 07/23 3 15179 07/24 4 15180 5 15181 6 15182 7 15183 07/28 8 15184 07/29 

which can then be transferred to the scale as follows:

scale_x_continuous(breaks = xscale$breaks, labels = xscale$labels)

+14
Jul 10 '11 at 2:11
source share



All Articles