I have 3D data that are all dates. I want to plot them with a contour. I have almost what I want with geom_contour_filled of package ggplot2 but I struggle to obtain a decent legend as dates (I'd like to use date_labels = "%b %d").
Here is an example code:
library(tidyverse)
predictions <- expand.grid(Var1 = 11437:11476, Var2 = 11475:11510)
predictions$Pred <- predictions[, 1] * (-1.60351) + predictions[, 2] * (-0.9927131) + (41231.33)
ggplot(predictions) +
aes(x = as.Date(Var1), y = as.Date(Var2), z = Pred) +
geom_contour_filled() +
scale_x_date() +
scale_y_date()
Using scale_fill_date returns an error because Pred is not in a date format. However, as.Date(Pred) or as.Date(floor(Pred)) returns this error (sorry for my Frenglish error messages):
Messages d'avis :
1: Dans pretty_isoband_levels(names(isobands)) :
NAs introduits lors de la conversion automatique
2: Dans pretty_isoband_levels(names(isobands)) :
NAs introduits lors de la conversion automatique
3: Computation failed in `stat_contour_filled()`.
Caused by error in `levels<-`:
! factor level [2] is duplicated
I infer that geom_contour_filled considers date objects in its z aesthetic as discrete. So I tried to transform the breaks and labels into what I would like:
months <- month(as.Date(min(predictions$Pred))):(month(as.Date(max(predictions$Pred))) + 1)
get_breaks <- sort(ymd(c(paste("2001", months, "01", sep = "-"), paste("2001", months, "15", sep = "-"))))
labels <- c()
for (the_break in 1:(length(get_breaks)))
labels <- c(labels, paste(month(get_breaks[the_break], label = TRUE), day(get_breaks[the_break])))
I managed to set the breaks and to prepare the labelling with guides(fill = guide_colorsteps(show.limits = TRUE)) but I don't see where I could give new labels since neither geom_contour_filled nor guide_colorsteps have a labels argument.
I thought the solution was here: Manually Set Scale of contour plot using geom_contour_filled
But I get this message in scale_fill_manual:
Erreur dans discrete_scale(aesthetic, name = name, palette = pal, breaks = breaks, :
argument formel "palette" correspondant à plusieurs arguments fournis
My last resource is to use Inkscape to modify the labelling ad hoc but I'd rather avoid this non-sustainable solution.