4

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

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
Koot6133
  • 1,428
  • 15
  • 26

1 Answers1

5

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

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
  • Thanks for the great workaround. The graph looks like my desired result. Unfortunately my hoover and legend now show all the traces. Is there a way to show it as a single trace? – Koot6133 Aug 03 '22 at 14:48
  • 1
    You can assign both traces to the same legendgroup and hide one of the legend items. This strategy is shown [here](https://stackoverflow.com/a/63629831/9841389). – ismirsehregal Aug 03 '22 at 17:45