如何从情节中删除痕迹

How to remove trace from the plot

我想从绘图和下面的图例中删除 NA 迹线。

  plot_ly(data = bData,  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',  
              symbol = ~Sym,  symbols = c('circle-open','x-open','diamond-open') ,
              text = ~paste(" Security: ", bData$Security, "<br>",
                            "Currency: ", bData$Crncy, "<br>",
                            "YTM: ", bData$YTM,"<br>",
                            "DM: ", bData$DM) ,
              hoverinfo = 'text',legendgroup = 'group1'
      ) %>%
        add_trace(x = ~`Maturity Date`, y =  ~YVal , symbol=~Crncy,legendgroup = 'group2')

试试这个。您可以在新数据框中隔离没有任何值的数据,然后绘制它。在此示例中,我将省略 Sym 变量中的 None 值,但如果您有 NA,请使用 !is.na(),因为我还为您添加了一行新代码。这里的代码:

library(plotly)
#New data example
bData2 <- bData[bData$Sym!='None',]
#For your real data
bData2 <- bData[!is.na(bData$Sym),]
#Code
plot_ly(data = bData2,  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',  
        symbol = ~Sym,  symbols = c('circle-open','x-open','diamond-open') ,
        text = ~paste(" Security: ", bData2$Security, "<br>",
                      "Currency: ", bData2$Crncy, "<br>",
                      "YTM: ", bData2$YTM,"<br>",
                      "DM: ", bData2$DM) ,
        hoverinfo = 'text',legendgroup = 'group1'
) %>%
  add_trace(x = ~`Maturity Date`, y =  ~YVal , symbol=~Crncy,legendgroup = 'group2')

输出省略 None:

更新: 试试这个 hack,将属于 None class 的值替换为 NA,首先将因子转换为字符然后再回到因素。真正的 NA 将被 plotly 函数删除。这里的代码:

#Replace
bData$Sym <- as.character(bData$Sym)
bData$Sym[bData$Sym=='None']<-NA
bData$Sym <- as.factor(bData$Sym)
#Code
plot_ly(data = bData,  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',  
        symbol = ~Sym,  symbols = c('circle-open','x-open','diamond-open') ,
        text = ~paste(" Security: ", bData$Security, "<br>",
                      "Currency: ", bData$Crncy, "<br>",
                      "YTM: ", bData$YTM,"<br>",
                      "DM: ", bData$DM) ,
        hoverinfo = 'text',legendgroup = 'group1'
) %>%
  add_trace(x = ~`Maturity Date`, y =  ~YVal , symbol=~Crncy,legendgroup = 'group2')

输出:

或者也试试这个,复制 YVal 并为第一个变量设置 NA

#Replace 2
bData$YVal2 <- bData$YVal
bData$Sym <- as.character(bData$Sym)
bData$Sym[bData$Sym=='None']<-NA
bData$YVal[is.na(bData$Sym)]<-NA
bData$Sym <- as.factor(bData$Sym)
#Code
plot_ly(data = bData,  x = ~`Maturity Date`, y =  ~YVal,  type = 'scatter', mode='markers',  
        symbol = ~Sym,  symbols = c('circle-open','x-open','diamond-open') ,
        text = ~paste(" Security: ", bData$Security, "<br>",
                      "Currency: ", bData$Crncy, "<br>",
                      "YTM: ", bData$YTM,"<br>",
                      "DM: ", bData$DM) ,
        hoverinfo = 'text',legendgroup = 'group1'
) %>%
  add_trace(x = ~`Maturity Date`, y =  ~YVal2 , symbol=~Crncy,legendgroup = 'group2')

输出: