Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

na

plotly

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

like image 328
Koot6133 Avatar asked Oct 20 '25 20:10

Koot6133


1 Answers

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

like image 87
ismirsehregal Avatar answered Oct 22 '25 09:10

ismirsehregal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!