有条件的阴影

时间:2016-07-29 12:23:29

标签: r plotly

我正在使用R界面绘制两个步骤函数来绘制和阴影它们之间的空间,如下所示:

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")

给了我以下图片:

enter image description here

我有什么办法可以:

  • 改变阴影的颜色,与线条的颜色无关?
  • 使阴影的颜色取决于两条线之间的差异是正还是负?

1 个答案:

答案 0 :(得分:3)

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

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

代码:

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()

结果:

enter image description here

通过在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值如下: enter image description here