-1

I am trying to making plots using ggplot in R and I have the same problem that was discussed below.

Date axis labels in ggplot2 is one day behind

My data ranges from 2016-09-01 to 2016-09-30, but labels in plots say 2016-08-31 is the first day of data. I solved the problem with the solution in the previous question, which is:

ggplot(df, aes(x, y)) + 
    geom_point() + 
    scale_x_datetime(breaks =df$x , labels = format(df$x, "%Y-%m-%d")) 

(Is this to set breaks and labels by taking exact dates from the data?)

Anyways, I have a new problem, dates match to labels well now but the plot does not look good.

see my plot here

I am not complaining length of dates is too long, but I don't like I can't set breaks and labels by a week or a certain number of days with the solution above. Also, I have many missing dates.

What should I do to solve this problem? I need a new solution.

Community
  • 1
  • 1
  • You can just set the format without the breaks with `scale_x_date(date_labels = '%F')`. If you need to set breaks, set more spaced ones, not every x value. Also, you should provide some sample data in your question to make it [reproducible](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – alistaire Sep 30 '16 at 01:37
  • @alistaire `scale_x_date(date_labels = '%F')` was already used when I faced the first problem mentioned, which is that dates did not match labels on the x-axis :( – Min-hyung Lee Sep 30 '16 at 03:57
  • @alistaire I did not provide the data because I thought if I have uploaded data as raw data, it would not make this problem. The data was made by several processes on R working space. Thanks for your answer. – Min-hyung Lee Sep 30 '16 at 04:04

2 Answers2

2

Just use this if you want your dates to appear vertically (that way you can see all your dates):

ggplot(df, aes(x, y)) + 
geom_point() + 
scale_x_datetime(breaks =df$x , labels = format(df$x, "%Y-%m-%d")) +
theme(axis.text.x = element_text(angle=90, vjust = 0.5))
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
0

I found the solution... Maybe my question was not described here in detail. My solution for the situation where dates did not match to values on an axis and I wanted to make plots look better is:

# set breaks first by seq.POSIXt
breaks.index <- seq.POSIXt(from=as.POSIXct(strftime("2020-01-01", format="%Y-%m-%d"), format="%Y-%m-%d"), to=as.POSIXct(strftime("2020-12-31", format="%Y-%m-%d"), format="%Y-%m-%d"), by="1 week")

and

# plot
plot <- ggplot(data, aes(x=date, y=y)
+scale_x_datetime(breaks = breaks.index, labels = format(breaks.index, "%Y-%m-%d"))
plot

.

Though I don't understand what is different from using scale_x_date(date_labels ='%F') and how this code works, it works.