简体   繁体   中英

Colors and text annotations in Plotly R - interactive mode

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 eg 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? 在此处输入图片说明

Appreciate your suggestions / inputs.

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

使用图例组绘图

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM