【问题标题】:Dynamic shape selection in plotlyplotly中的动态形状选择
【发布时间】:2020-09-28 13:57:25
【问题描述】:

为了突出显示时间序列中的区域,我使用layout > shapes 对象,如下所述:How to add colored background bars in plotly.js chart

现在这些背景形状中的每一个都有一个“类型”,我希望用户能够显示/隐藏特定类型,就像跟踪一样(例如,仅显示 V4 和 V5,隐藏 V3,如示例下面)。

这可能吗?

【问题讨论】:

    标签: plotly r-plotly


    【解决方案1】:

    这原则上可以通过使用形状的轨迹插入来指定背景区域来实现。这样背景区域就会出现在图例中。使用一些随机示例数据试试这个:

    library(plotly)
    set.seed(42)
    d <- data.frame(
      x=as.Date(c('2015-02-01', '2015-02-02', '2015-02-03', '2015-02-04', '2015-02-05',
         '2015-02-06', '2015-02-07', '2015-02-08', '2015-02-09', '2015-02-10',
         '2015-02-11', '2015-02-12', '2015-02-13', '2015-02-14', '2015-02-15',
         '2015-02-16', '2015-02-17', '2015-02-18', '2015-02-19', '2015-02-20',
         '2015-02-21', '2015-02-22', '2015-02-23', '2015-02-24', '2015-02-25',
         '2015-02-26', '2015-02-27', '2015-02-28')),
      y=runif(28, 350, 550)
    )
    d
    
    range_y <- list(min = floor(min(d$y) / 100) * 100, max = ceiling(max(d$y) / 100) * 100)
    
    shape1 <- data.frame(x = as.Date(c('2015-02-01', '2015-02-08')), y = c(range_y$max, range_y$max))
    shape2 <- data.frame(x = as.Date(c('2015-02-23', '2015-02-27')), y = c(range_y$max, range_y$max))
    
    plot_ly(x=~x, y=~y) %>% 
      add_trace(data = d, mode = "lines+markers", type = "scatter") %>% 
      add_trace(data = shape1, mode = "none", fill = "tozeroy", name = "type1") %>% 
      add_trace(data = shape2, mode = "none", fill = "tozeroy", name = "type2") %>% 
      layout(yaxis = list(range = c(range_y$min, range_y$max)))
    

    【讨论】:

    • 这确实是一个可行的解决方案。 +1。请注意,在这种情况下必须指定 y 轴的限制。我最初选择使用layout &gt; shape 的原因是因为条形的垂直范围可以从-InfInf
    • 是的。这是使用跟踪的一个缺点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 2012-03-02
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多