gpt4 book ai didi

R plot_ly() : adding multiple vertical lines to a plot based on time data

转载 作者:行者123 更新时间:2023-12-05 03:49:54 25 4
gpt4 key购买 nike

我需要一些帮助来绘制基于时间数据的多条垂直线。我的时间数据数据框定义如下:

v.years <- as.Date(c("2004-01-01", "2005-01-01", "2006-01-01", "2007-01-01", "2008-01-01", "2009-01-01",
"2010-01-01", "2011-01-01", "2012-01-01", "2013-01-01", "2014-01-01", "2015-01-01",
"2016-01-01", "2017-01-01", "2018-01-01", "2019-01-01", "2020-01-01", "2021-01-01"))
df.dateYears <- as.data.frame(v.years)

我的 plotly 代码如下所示:

p <- plot_ly(dt.allDataFvsS, x = dt.allDataFvsS$date, y = dt.allDataFvsS$meanDifference, mode = 'lines',
type = 'scatter', line = list(color = "#007d3c"), text = ~forwardProduct,
hovertemplate = paste("<b>%{text} vs. Spot</b><br>", "%{xaxis.title.text}: %{x}<br>",
"%{yaxis.title.text}: %{y}<br><extra></extra>")) %>%
add_trace(x = as.Date("2018-10-01"), type = 'scatter', mode = 'lines',
line = list(color = "red", dash = "dash"), text = "Price Zone Separation",
hovertemplate = paste("<b>%{text}</b><br>", "%{xaxis.title.text}: %{x}<br><extra></extra>")) %>%
layout(title = "Average Price Difference Forward vs. Spot", xaxis = list(title = "Date"),
yaxis = list(title = "EUR/MWh"), showlegend = FALSE) %>%

正如您在我上面的代码中看到的那样,我知道如何针对单个日期执行此操作,我在其中使用了以下内容:

trace_add(x = as.Date("2018-10-01"), ...)

我的 plotly 实际上是这样的: Rplot

所以,我的问题是:如何绘制与我的数据框 df.dateYears 中的时间数据完全匹配的多条垂直线?

最佳答案

我建议使用循环和您在问题中提到的日期的原始向量来使用这种方法。我已经添加了示例数据并修改了您的日期向量,但是对于您的原始数据,它必须可以正常工作:

library(plotly)
library(dplyr)
set.seed(123)
#Sample data
mydata <- data.frame(date=seq(as.Date('2017-01-01'),as.Date('2021-12-31'),length.out = 30),
meanDifference=round(runif(30,0,15),0),stringsAsFactors = F)
#Plot
p <- plot_ly(mydata, x = ~date, y = ~meanDifference, mode = 'lines',
type = 'scatter', line = list(color = "#007d3c"), text = ~meanDifference)
#New data
v.years <- as.Date(c("2017-01-01", "2018-01-01", "2019-01-01", "2020-01-01", "2021-01-01"))
#Add lines with loop
for(i in 1:length(v.years))
{
p <- p %>%
add_trace(x = v.years[i], type = 'scatter', mode = 'lines',
line = list(color = "red", dash = "dash"), text = "Price Zone Separation")
}

输出:

enter image description here

关于R plot_ly() : adding multiple vertical lines to a plot based on time data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63705027/

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