Search code examples
rplotlynar-plotly

How to hide the (interpolated) fill in plotly when there are NA values in the data? (Using R)


I am trying to plot a line graph with fill and NA values. Plotly automatically fills the part with NA values where I want it to be empty. What is the best way to get the correct graph?

It is not an option to set the NA values to 0. I am also using a hoover and do not want to have a result of 0 while hovering over the line.

Example R data + code:

library(plotly)

set.seed(1)
A = data.frame(x = 1900:2000, value=cumsum(rnorm(101)))
A[40:70, 2:3] = NA

fig <- plot_ly(x = A$x, y = A$value, type = 'scatter', mode = 'lines', fill = 'tozeroy')
fig

Result: enter image description here

Desired Result: enter image description here


Solution

  • You could split the data into separate traces to achive this:

    library(plotly)
    library(data.table)
    
    set.seed(1)
    A = data.frame(x = 1900:2000, value = cumsum(rnorm(101)))
    A[40:70, 2] = NA
    
    setDT(A)
    A[, id := rleid(is.na(value))]
    
    fig <- plot_ly(
        data = A,
        x = ~ x,
        y = ~ value,
        type = 'scatter',
        mode = 'lines',
        fill = 'tozeroy',
        split = ~ id,
        color = I("#1f77b4"),
        showlegend = FALSE
      )
    fig
    

    result