geom_raster渲染异常求助:相关可视化问题后续图形渲染故障
Hey there! I know you previously asked about creating a Status by duration bar visualisation and now you're hitting a snag where the graph won't render properly. Let's walk through fixing this step by step.
First, let's clean up and complete the test data you provided (since it was truncated):
# Complete test data (filling in truncated timestamp values for reproducibility) 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, 1493737200000, 1493650800000, 1493564400000, 1493478000000, 1493391600000, 1493305200000, 1493218800000, 1493132400000, 1493046000000, 1492959600000, 1492873200000, 1492786800000, 1492700400000, 1492614000000, 1492527600000, 1492441200000, 1492354800000, 1492268400000, 1492182000000) ), class = "data.frame", row.names = c(NA, -20L) )
Common Causes of Rendering Failure & Fixes
Here are the most likely issues stopping your graph from showing up, plus how to fix them:
Millisecond timestamp not converted to readable datetime: Your
timestampvalues are in milliseconds since epoch, which R doesn't recognize as dates by default. We need to convert them first:# Convert milliseconds to POSIXct datetime testData$datetime <- as.POSIXct(testData$timestamp / 1000, origin = "1970-01-01")Missing a clear duration calculation: To visualize duration by status, you need to calculate the time between consecutive status changes. Let's add that:
# Calculate time difference between consecutive entries testData$duration <- c(diff(testData$datetime), NA) # Keep only rows where we have valid duration (drop last row) plotData <- testData[-nrow(testData), ]Incorrect mapping in your plotting function: Using
ggplot2(the most common R plotting library), here's a working example to create the status duration bar chart:library(ggplot2) ggplot(plotData, aes(x = datetime, y = duration, fill = result)) + geom_col(position = "stack") + scale_fill_manual(values = c("FAILURE" = "#ff4c4c", "SUCCESS" = "#4caf50")) + labs(title = "Status Duration Over Time", x = "Timestamp", y = "Duration (seconds)", fill = "Result") + theme_minimal()
Why This Works
- Converting the timestamp to a proper datetime format lets R correctly plot the x-axis as a time series.
- Calculating
durationgives us the length of time each status was active, which is the core of your visualization. - The
geom_col()call maps the duration to the bar height, with fill color representing success/failure, making the status changes clear.
If you were using a different plotting library (like base R or plotly), let me know and we can adjust the code accordingly!
内容的提问来源于stack exchange,提问作者Froom2

