划分线条图R Shiny

时间:2018-08-02 13:29:48

标签: r shiny plotly dt

我想将线图分为两个区域(左和右)。我在绘制相同的历史价值和预测价值,并且梦想着拥有不同的历史和预测价值背景。我更喜欢使用Plotly库。

有人知道这是否可行吗?

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以将rect shape添加到layout中,其尺寸与测量数据和预测数据相同。创建两条单独的跟踪,一条用于真实数据,一条用于预测,或者使用合并的跟踪。

两条痕迹

set.seed(42)

x <- sort(rnorm(25)) 
y <- x + rnorm(5)

predict(lm(y ~ x))
new_x <- seq(max(x) + 0.1, 5, 1)
new <- data.frame(x = new_x)
pred <- predict(lm(y ~ x), new, se.fit = TRUE)
new_y <- unname(pred$fit)

p <- plot_ly()
p <- add_trace(p, x = x, y = y, name = 'real', type = 'scatter', mode = 'scatter+lines', line = list(shape = 'spline'))
p <- add_trace(p, x = new_x, y = new_y, name = 'predicted', type = 'scatter', mode = 'scatter+lines', line = list(shape = 'spline'))


p <- layout(p,
            shapes = list(
              list(type = "rect",
                   fillcolor = "blue", line = list(color = "blue"), opacity = 0.3,
                   x0 = min(x), x1 = max(x), xref = "x",
                   y0 = min(y), y1 = max(new_y), yref = "y"),
              list(type = "rect",
                   fillcolor = "red", line = list(color = "blue"), opacity = 0.2,
                   x0 = max(x), x1 = max(new_x), xref = "x",
                   y0 = min(y), y1 = max(new_y), yref = "y")))

p

enter image description here

一条痕迹

set.seed(42)

x <- sort(rnorm(25)) 
y <- x + rnorm(5)

predict(lm(y ~ x))
new_x <- seq(max(x) + 0.1, 5, 1)
new <- data.frame(x = new_x)
pred <- predict(lm(y ~ x), new, se.fit = TRUE)
new_y <- unname(pred$fit)

all_x = c(x, new_x)
all_y = c(y, new_y)
p <- plot_ly()
p <- add_trace(p, x = all_x, y = all_y, type = 'scatter', mode = 'scatter+lines', line=list(shape='spline'))

p <- layout(p,
            shapes = list(
              list(type = "rect",
                   fillcolor = "blue", line = list(color = "blue"), opacity = 0.3,
                   x0 = min(x), x1 = max(x), xref = "x",
                   y0 = min(y), y1 = max(new_y), yref = "y"),
              list(type = "rect",
                   fillcolor = "red", line = list(color = "blue"), opacity = 0.2,
                   x0 = max(x), x1 = max(new_x), xref = "x",
                   y0 = min(y), y1 = max(new_y), yref = "y")))

p

enter image description here