使用plotly过滤链接视图中的图例 [英] Filter legend in linked views with plotly

查看:50
本文介绍了使用plotly过滤链接视图中的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理链接图(类似于

I am working on a linked plot (similar to The SharedData plot pipeline from Carson Sievert in plotly for R. The plot shows a legend for one item I currently hover over. However, right now the legend shows two elements, one for the bar chart and one for the line chart.

  • How do I delete the first legend element (the red square for the bar chart) and keep only the legend for the line chart (red line)?

Here is current code:

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

It was mentioned somewhere that the final removal of the legend element may work, but its not working for me here.

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

解决方案

If Plotly doesn't provide us a method to hide legends created by highlight, then let's use Plotly's own functions to do so.

Javascript code which is needed to hide the trace once:

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

In this case it is always the third element [2] which needs its legend hidden, in general it would be preferable to get the index dynamically based on some conditions.

Let's add this to Plotly's on_click event to make sure that the legend will be invisible in the future as well.

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

And finally add everything to the output and we are good.

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

这篇关于使用plotly过滤链接视图中的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆