[英]R plotl_ly: Points of time data different color (past data lighter, current data darker)
我需要一些帮助来绘制时间数据。 我的数据框定义如下:
date <- c("2018-01-02", "2018-01-03", "2018-01-04", "2018-01-05", "2019-01-02", "2019-01-03", "2020-01-01",
"2020-01-09", "2020-01-10", "2020-05-15")
prod1 <- c(43.10, 42.56, 41.77, 41, 40.79, 41.03, 40.98, 41.13, 41.98, 40.81)
prod2 <- c(19.442, 19.320, 19.204, 18.918, 19.041, 19.452, 19.516, 19.177, 18.974, 19)
df.dataCorrelation <- data.frame(date, prod1, prod2)
该图如下所示:
我现在想要的是 2018 年的点比 2019 年的点颜色更浅,依此类推。 也就是说,数据越新,颜色越强/越深。
有谁知道我怎么能做到这一点? 实际上,我的数据框要大得多,并且每年包含更多信息。
编辑:回归线
fit <- lm(prod2 ~ prod1, data = df.dataCorrelation)
fitData <- data.frame((prod1 = 20:60))
prediction <- predict(fit, fitData, se.fit = TRUE)
fitData$fitted <- prediction$fit
绘图代码:
df.dataCorrelation$Year <- format(as.Date(df.dataCorrelation$date), '%Y')
plotCorr <- plot_ly(data = df.dataCorrelation, x = ~prod1, y = ~prod2, color = ~Year, colors = "Greens",
marker = list(size = 10, line = list(color = "black", width = 2))) %>%
add_trace(data = fitData, x = ~prod1, y = ~fitted, mode = "lines", type = "scatter",
line = list(color = "#007d3c", width = 3))
如何绘制回归线?
我已经检查了plotly
文档,当您将数据添加为单独的跟踪时,不透明度是可能的。 我试图这样做,但情节的主要思想丢失了。 我会建议一种方法,您可以按年份设置颜色。 这里的代码:
library(plotly)
library(dplyr)
#Data
date <- c("2018-01-02", "2018-01-03", "2018-01-04", "2018-01-05", "2019-01-02", "2019-01-03", "2020-01-01",
"2020-01-09", "2020-01-10", "2020-05-15")
prod1 <- c(43.10, 42.56, 41.77, 41, 40.79, 41.03, 40.98, 41.13, 41.98, 40.81)
prod2 <- c(19.442, 19.320, 19.204, 18.918, 19.041, 19.452, 19.516, 19.177, 18.974, 19)
df.dataCorrelation <- data.frame(date, prod1, prod2,stringsAsFactors = F)
#Extract year
df.dataCorrelation$Year <- format(as.Date(df.dataCorrelation$date),'%Y')
#Plot
plot_ly(data = df.dataCorrelation, x = ~prod1, y = ~prod2,color=~Year,
marker = list(size = 10,
line = list(color = 'rgba(152, 0, 0, .8)',
width = 2)))
输出:
我希望这对你有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.