JosvdBerg
JosvdBerg

Reputation: 31

Heatmap plotting time against date ggplot

I would like to make a heatmap with ggplot. The results should be something like this (the y-axis needs to be reversed though):

heatmap time/date

A subset of example data is below. For the actual application the dataframe has 1000+ users instead of only 3. The gradient filling should be based on the value of the users.

Date <- seq(
  from = as.POSIXct("2016-01-01 00:00"),
  to  = as.POSIXct("2016-12-31 23:00"),
  by = "hour"
)    
user1 <- runif(length(Date), min = 0, max = 10)
user2 <- runif(length(Date), min = 0, max = 10)
user3 <- runif(length(Date), min = 0, max = 10)
example <- data.frame(Date, user1, user2, user3)

example$hour <- format(example$Date, format = "%H:%M")
example$total <- rowSums(example[,c(2:4)])

I have tried several things by using the (fill = total) argument in combination with geom_tile, geom_raster and stat_density2d (like suggested in similar posts here). An example below:

ggplot(plotHuishoudens, aes(Date, hour, fill = Total)) +
  geom_tile() +
  scale_fill_gradient(low = "blue", high = "red")

Which only shows individual points and not shows the y axis like a continuous variable (scale_y_continuous also did not help with this), although the variable is a continuous one?

How can I create a heatmap like the example provided above? And how could I make a nice cut-off on the y axis (e.g. per 3 hours instead of per hour)?

Upvotes: 0

Views: 1743

Answers (1)

Jrm_FRL
Jrm_FRL

Reputation: 1433

The way your data is defined, you won't come to the desired output because example$Date is a POSIXct object, that is a date and an hour.

So, you must map your graph to the day only:

ggplot(data = example) + 
  geom_raster(aes(x=as.Date(Date, format='%d%b%y'), y=hour, fill=total)) + 
  scale_fill_gradient(low = "blue", high = "red")

enter image description here

For your second question, you can group hours like this:

example <- example %>% 
  group_by(grp = rep(row_number(), length.out = n(), each = 4)) %>%
  summarise(Date = as.Date(sample(Date, 1), format='%d%b%y'),
            total = sum(total),
            time_slot = paste(min(hour), max(hour), sep = "-"))

ggplot(data = example) + 
  geom_raster(aes(x = Date, y = time_slot, fill = total)) + 
  scale_fill_gradientn(colours = (cet_pal(6, name = "inferno"))) # I like gradients from "cetcolor" package

enter image description here

Upvotes: 3

Related Questions