geom_raster未按预期呈现

时间:2018-03-29 07:47:30

标签: r ggplot2 geom-raster

我之前曾问过一个相关的问题(Status by duration bar visualisation),但我现在遇到了实际渲染图表的问题...

以下是复制我目前所拥有的代码:

    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)

我明白了:

enter image description here

我有点期待它填补行间的差距:(就像我之前的问题的答案那样: https://stackoverflow.com/a/49492933/2295284

1 个答案:

答案 0 :(得分:2)

这里有很多选择。一个是绘制细分:

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