gpt4 book ai didi

r - plotly中的条件阴影

转载 作者:行者123 更新时间:2023-12-04 10:52:44 24 4
gpt4 key购买 nike

我正在使用 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

有什么办法可以:

  • 独立于线条的颜色改变底纹的颜色?
  • 使阴影的颜色成为两条线之间的差异是正数还是负数的函数?

最佳答案

我设法在 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()

结果:

enter image description here

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

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

关于r - plotly中的条件阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38658766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com