【问题标题】:Filter legend in linked views with plotly使用 plotly 过滤链接视图中的图例
【发布时间】:2018-02-04 18:53:21
【问题描述】:

我正在制作一个链接图(类似于 Carson Sievert 的 The SharedData plot pipeline 在 plotly for R 中。该图显示了我目前悬停在的一个项目的图例。但是,现在图例显示了两个元素,一个用于条形图和折线图。

  • 如何删除第一个图例元素(条形图的红色方块)并只保留折线图的图例(红线)?

这是当前代码:

library(ggplot2)
library(crosstalk)
library(plotly)

sd <- SharedData$new(txhousing, ~city)

base <- plot_ly(sd, color = I("black")) %>%
        group_by(city) %>%
        layout(showlegend = TRUE)

p1 <- base %>%
      summarise(has = sum(is.na(median))) %>%
      filter(has > 0) %>%
      arrange(has) %>%
      add_bars(x = ~has, y = ~factor(city, levels = city), 
       hoverinfo = "none", showlegend = FALSE) %>%
      layout(
      barmode = "overlay",
        xaxis = list(title = "Number of months missing"),
        yaxis = list(title = "")
      ) 

p2 <- base %>%
   add_lines(x = ~date, y = ~median, alpha = 0.3, showlegend = FALSE) %>%
   layout(xaxis = list(title = ""))

gp <- subplot(p1, p2, titleX = TRUE, widths = c(0.3, 0.7)) %>% 
  layout(margin = list(l = 120)) %>%
  highlight(color = "red",
        defaultValues = "Victoria",
        selected = attrs_selected(showlegend = TRUE, mode = "lines"
    ))

 gp

有人提到,最终删除图例元素可能会起作用,但在这里对我不起作用。

gp$x$data[[1]]$showlegend <- FALSE

【问题讨论】:

  • 据我所知,您不能直接在 Plotly 中执行此操作。但是,您可以将 Javascript 代码添加到您的绘图中以处理您需要的内容。

标签: r plot charts legend plotly


【解决方案1】:

如果 Plotly 没有为我们提供隐藏 highlight 创建的图例的方法,那么让我们使用 Plotly 自己的函数来做到这一点。

隐藏一次跟踪所需的Javascript代码:

var updated = {showlegend: false};
var myPlot = document.getElementsByClassName('plotly')[0];
Plotly.restyle(myPlot, updated, [2]);

在这种情况下,总是需要隐藏其图例的第三个元素[2],通常最好根据某些条件动态获取索引。

让我们将此添加到 Plotly 的 on_click 事件中,以确保该图例在未来也将不可见。

myPlot.on('plotly_click', function(data){
  Plotly.restyle(myPlot, updated, [2]);
});

最后将所有内容添加到输出中,我们很好。

javascript <- "
var updated = {showlegend: false};
var myPlot = document.getElementsByClassName('plotly')[0];
Plotly.restyle(myPlot, updated, [2]);
myPlot.on('plotly_click', function(data){
  Plotly.restyle(myPlot, updated, [2]);
});
"

w <- plotly::as_widget(gp)
w <- htmlwidgets::prependContent(w, onStaticRenderComplete(javascript), data=list(''))
htmlwidgets::saveWidget(w, "cities.html")
w

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 2018-08-14
    • 2019-11-04
    • 2017-06-07
    相关资源
    最近更新 更多