rggplot2geom-raster

geom_raster not rendering as expected


I have previously asked a related question (Status by duration bar visualisation), but I am now having trouble with the graph actually rendering...

Here is the code to replicate what I currently have:

    testData <- structure(list(result = c("SUCCESS", "SUCCESS", "SUCCESS","SUCCESS", 
"SUCCESS", "SUCCESS", "SUCCESS", "SUCCESS", "SUCCESS", "SUCCESS", 
"SUCCESS", "SUCCESS", "FAILURE", "FAILURE", "FAILURE", "SUCCESS", 
"SUCCESS", "SUCCESS", "SUCCESS", "SUCCESS"), timestamp = c(1493801810680, 
1493737048748, 1493714474308, 1493382713281, 1493735761855, 1493288844857, 
1493282996949, 1493287445076, 1493802680235, 1493217700328, 1493820960231, 
1493826923306, 1493892937587, 1493894930889, 1493900922844, 1493913941074, 
1493988183593, 1493993210175, 1494232458444, 1494241235864)), .Names = c("result", 
"timestamp"), row.names = c(NA, 20L), class = "data.frame")

    library(plyr)

    testData$timestamp <- anytime(testData$timestamp/1000)
    testData$time <- testData$timestamp
    testData$timestamp <- NULL

    testData <- testData[order(testData$time),]

    getNextTime <- function(time) testData$time[which(grepl(time, testData$time)) + 1]

    testData$nextTime <- sapply(testData$time, getNextTime)

    as.POSIXct(testData$time[is.na(testData$nextTime)])
    testData$nextTime <- as.POSIXct(testData$nextTime, origin = "1970-01-01")
    testData$nextTime[is.na(testData$nextTime)] <- testData$time[is.na(testData$nextTime)] + 60^2

    testFunc <- function(data) {
      data.frame(
        time = seq(data$time[1], data$nextTime[1], by=60^2),
        result = data$result[1])
    }

    test <- dlply(testData,time ~ time, testFunc)

    df <- ldply(test, data.frame)
    df$y <- 0

    df$z[df$result == "SUCCESS"] <- 1
    df$z[df$result == "FAILURE"] <- 2
    df$z <- factor(df$z)

library(ggplot2)
ggplot(df, aes(time, y, fill = z)) + 
  geom_raster() + 
  ylim(-10, 10) +
  scale_fill_manual(values = 2:3)

I get this:

enter image description here

I was kind of expecting it to fill in the gaps between the lines :( like the answer to my previous question does: https://stackoverflow.com/a/49492933/2295284


Solution

  • There is a bunch of options here. One is to just plot segments:

    library(ggplot2)
    ggplot(df, aes(time, y, xend = dplyr::lead(time), yend = y, color = z)) + 
      geom_segment(size = 5) + 
      ylim(-10, 10) +
      scale_color_manual(values = 2:3)
    

    enter image description here