【发布时间】:2021-04-15 11:01:02
【问题描述】:
我正在使用 R 编程语言。我正在尝试学习如何在图表上叠加点,然后将它们可视化。
使用下面的代码,我可以生成一些时间序列数据,按月聚合它们,取平均值/最小值/最大值,并绘制下图:
library(xts)
library(ggplot2)
library(dplyr)
library(plotly)
library(lubridate)
set.seed(123)
#time series 1
date_decision_made = seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")
property_damages_in_dollars <- rnorm(731,100,10)
final_data <- data.frame(date_decision_made, property_damages_in_dollars)
#####aggregate
final_data$year_month <- format(as.Date(final_data$date_decision_made), "%Y-%m")
final_data$year_month <- as.factor(final_data$year_month)
f = final_data %>% group_by (year_month) %>% summarise(max_value = max(property_damages_in_dollars), mean_value = mean(property_damages_in_dollars), min_value = min(property_damages_in_dollars))
####plot####
fig <- plot_ly(f, x = ~year_month, y = ~max_value, type = 'scatter', mode = 'lines',
line = list(color = 'transparent'),
showlegend = FALSE, name = 'max_value')
fig <- fig %>% add_trace(y = ~min_value, type = 'scatter', mode = 'lines',
fill = 'tonexty', fillcolor='rgba(0,100,80,0.2)', line = list(color = 'transparent'),
showlegend = FALSE, name = 'min_value')
fig <- fig %>% add_trace(x = ~year_month, y = ~mean_value, type = 'scatter', mode = 'lines',
line = list(color='rgb(0,100,80)'),
name = 'Average')
fig <- fig %>% layout(title = "Average Property Damages",
paper_bgcolor='rgb(255,255,255)', plot_bgcolor='rgb(229,229,229)',
xaxis = list(title = "Months",
gridcolor = 'rgb(255,255,255)',
showgrid = TRUE,
showline = FALSE,
showticklabels = TRUE,
tickcolor = 'rgb(127,127,127)',
ticks = 'outside',
zeroline = FALSE),
yaxis = list(title = "Dollars",
gridcolor = 'rgb(255,255,255)',
showgrid = TRUE,
showline = FALSE,
showticklabels = TRUE,
tickcolor = 'rgb(127,127,127)',
ticks = 'outside',
zeroline = FALSE))
fig
现在(在同一个图“图”上),对于每个月,我都试图以垂直方式绘制该月的所有观察结果。我正在尝试创建这样的东西:
通过一些数据操作,以下代码可以生成下图:plot( final_data$year_month, final_data$property_damages_in_dollars)
有人可以告诉我如何扩展此解决方案以用于绘图(即增强“无花果”对象)吗?
谢谢
【问题讨论】:
-
应该使用 geom_ribbon() 参数吗?
-
这些建议对您有何影响?
标签: r dplyr time-series plotly r-plotly