ggplot2 – R: ggplot is giving a wrong and obscure graph

Your code to convert the %m-$d-%Y dates into Date format is not working the way you intended.

dates <- c("1-2-2018", "1-3-2018")
for (i in 1:length(dates)) {
  dates[[i]] <- as.Date(dates[[i]], format = "%m-%d-%Y")
}
str(dates)
#chr [1:2] "17533" "17534"

Compare to

dates <- c("1-2-2018", "1-3-2018")
dates <- as.Date(dates, format = "%m-%d-%Y")
str(dates)
#Date[1:2], format: "2018-01-02" "2018-01-03"

We want the 2nd version, so the output is date format instead of character, so ggplot2 will sort it correctly and display reasonable breaks. Your character dates are being displayed for every single day, as text like “17533” — that’s why it looks so wrong. (The 2nd way is also more idiomatic for R, where most operations are vectorized and can be applied to the whole column at once instead of by manually creating loops for each element. More background: www.noamross.net/archives/2014-04-16-vectorization-in-r-why/)

The first version doesn’t work as you intended, because it asks R to replace each element of the character vector one by one, so it needs to coerce the dates to character data to fit the type of the rest of the vector, and in this case it does so by converting to numeric (days since 1970-01-01) and then converting that to text. So you’re getting the same thing as if you ran

as.character(as.numeric(as.Date(dates, format = "%m-%d-%Y")))

Read more here: Source link