plotly中的条件阴影

conditional shading in plotly

我正在使用 R 界面绘制两个阶梯函数,以在它们之间绘制和着色 space,如下所示:

df <- structure(list(datetime = structure(c(1469869200, 1469871000, 
1469872800, 1469874600, 1469876400, 1469878200, 1469880000, 1469881800, 
1469883600, 1469885400, 1469887200, 1469889000, 1469890800, 1469892600, 
1469894400, 1469896200, 1469898000, 1469899800, 1469901600, 1469903400, 
1469905200, 1469907000, 1469908800, 1469910600), tzone = "Europe/Berlin", class = c("POSIXct", 
"POSIXt")), ya = c(0, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 4, 5, 
5, 5, 7, 7, 7, 7, 5, 2, 0, 0), yb = c(0, 0, 1, 2, 3, 2, 2, 2, 
2, 2, 1, 1, 2, 3, 4, 6, 8, 8, 8, 8, 8, 4, 1, 0)), class = "data.frame", row.names = c(NA, 
-24L), .Names = c("datetime", "ya", "yb"))

df %>%
    plot_ly(x=datetime, y=ya, line = list(shape = "hv")) %>%
    add_trace(x=datetime, y=yb, line = list(shape = "hv"), fill = "tonexty")

这给了我下面的图片:

有什么办法吗:

我设法在 ggplot2 中构建它,然后使用 ggplotly() 转换为 plotly

通过单独创建线条和中间的矩形,您可以添加条件着色。

代码:

ggplot(df) + 
  geom_step(aes(x = datetime, y = ya), colour = "red") +  # Create the ya line
  geom_step(aes(x = datetime, y = yb), colour = "blue") + # Create the yb line
  geom_rect(aes(xmin = datetime,                # Create rectangles strarting at every datetime
                xmax = datetime + minutes(30),  # It should reach untill the next datetime
                ymin = ifelse(ya > yb, yb, ya), # Lower bound is the lowest of ya and yb
                ymax = ifelse(ya > yb, ya, yb), # Upper bound is highest of ya and yb
                fill = ya > yb))                # Colour the rectangles based on condition

ggplotly()

结果:

通过在 ggplotly 调用中使用 text 美学和 tooltip 选项,您可以调整最终绘图中悬停的内容。例如这段代码:

ggplot(df, aes(x = datetime)) + 
  geom_step(aes(y = ya, text = paste("ya: ",ya,", yb: ",yb, sep = ""), group = 1), colour = "red")  +
  geom_step(aes(y = yb, text = paste("ya: ",ya,", yb: ",yb, sep = ""), group = 1), colour = "blue") +
  geom_rect(aes(xmin = datetime,
                xmax = datetime + minutes(30),
                ymin = ifelse(ya > yb, yb, ya),
                ymax = ifelse(ya > yb, ya, yb),
                fill = ya > yb,
                text = paste("ya: ",ya,", yb: ",yb, sep = "")))

ggplotly(tooltip = c("x","text"))

你会给你显示时间和 ya 和 yb 值的工具提示吗?