1

Problem: The following code produces a plot which groups data based on color and annotates text on the respective y-data-points. When interacting with the plot (in the viewer pane), the selection of e.g. only model a4 (by clicking on the line) does not work correctly as the lines disappear for all other models but the according numbers won't. Any ideas how to fix this?

library(plotly)
library(data.table)
dt <- as.data.table(mpg)

plot_ly(dt[model %in% c("a4", "passat")],
        x = ~year,
        y = ~displ,
        color = ~model,
        colors = "Set1") %>% 
  add_lines() %>% 
  add_text(y = ~displ, 
           text = ~displ,
           textposition = "top right",
           showlegend = FALSE) %>% 
  layout(xaxis = list(title = ""),
         yaxis = list(title = "Anzahl"))

Below you can find a figure describing my problem. Once I select only a4 in the plotly chart, the passat line disappears however the numbers associated to this line remain.

Aim: How to modify the code such that not only the line disappears for a4/passat but also the associated numbers? enter image description here

Appreciate your suggestions / inputs.

rkraft
  • 495
  • 4
  • 16
  • Please take a look at [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), to modify your question, with a smaller sample taken from your data (check `?dput()`). Posting images of your data or no data makes it difficult to impossible for us to help you! – massisenergy Mar 17 '20 at 13:24

1 Answers1

2

The add_text statement has the option showlegend as FALSE, which effectively hides a potential second legend that would show/hide the text/numbers.

One strategy could be to use legendgroup to group the two legends together for lines and text, while still hiding the text legend. The group should be assigned to model in this case.

library(plotly)
library(data.table)

dt <- as.data.table(mpg)

plot_ly(dt[model %in% c("a4", "passat")],
        x = ~year,
        y = ~displ,
        color = ~model,
        colors = "Set1") %>% 
  add_lines(legendgroup = ~model) %>% 
  add_text(y = ~displ, 
           text = ~displ,
           textposition = "top right",
           showlegend = FALSE,
           legendgroup = ~model) %>% 
  layout(xaxis = list(title = ""),
         yaxis = list(title = "Anzahl"))

Plot

plotly plot using legendgroup

Ben
  • 28,684
  • 5
  • 23
  • 45