Filter legend in linked views using a graph

I am working on a related plot (similar to the outline of the SharedData plot from Carson Sievert in the plot for R. The plot shows a legend for one element that I find now. However, now the legend shows two elements: one for a histogram and one for a line chart.

  • How to remove the first element of a legend (red square for a histogram) and save only the legend for a line diagram (red line)?

Here is the 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 permanently deleting a legend item may work, but it does not work for me here.

gp$x$data[[1]]$showlegend <- FALSE
+4
source share
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

enter image description here

+2

Source: https://habr.com/ru/post/1684554/


All Articles