【问题标题】:divide background of line plot R Shiny分割线图的背景 R Shiny
【发布时间】:2019-01-10 07:16:27
【问题描述】:

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

有谁知道这是否可能以及如何做到这一点?

【问题讨论】:

    标签: r shiny plotly dt


    【解决方案1】:

    您可以将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
    

    一条痕迹

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      • 2012-07-03
      相关资源
      最近更新 更多