Home > Blockchain >  Plotly wrongly filling gaps based on color factor in R
Plotly wrongly filling gaps based on color factor in R

Time:02-06

I am simply trying to get every month of data to plot the same color.

Plotly is falsely plotting lines that connect each factor color together, generating a giant mess on the chart.

connectgaps = FALSE does not work, because the gaps are not in the data. They are being generated by plotly on the ~factor(month), which colors each month the same.

This has something to do with multiple observations of the factor, rather than just one. If the factor was based on year, rather than month, no line traces would occur.

How can I remove these lines? Thank you!

library(tidyverse)
library(lubridate)
library(plotly)

start_date <- as.Date('2020-1-1')  
end_date <- as.Date('2023-2-5')   

d1 <- tibble::tibble(date = seq(min(start_date), max(end_date), by = "1 day"))
d2 <- tibble::tibble(rnorm(1132,2))
d3 <- data.frame(d1,d2)
d3 <- d3 %>% mutate(month = month(date)) 

colnames(d3) <- c('date', 'var', 'month')

plot_ly(d3, x = ~date, y = ~var, type = "scatter", mode = "lines", color = ~factor(month), connectgaps =FALSE)

CodePudding user response:

You could add another column which is the year so you can group on each year using group_by to prevent connecting the lines per month for each year like this:

start_date <- as.Date('2020-1-1')  
end_date <- as.Date('2023-2-5') 

library(lubridate)
library(dplyr)
library(plotly)

d1 <- tibble::tibble(date = seq(min(start_date), max(end_date), by = "1 day"))
d2 <- tibble::tibble(rnorm(1132,2))
d3 <- data.frame(d1,d2)
d3 <- d3 %>% mutate(month = month(date),
                    year = year(date)) 

colnames(d3) <- c('date', 'var', 'month', 'year')
d3 %>%
  group_by(year) %>%
  plot_ly(x = ~date, y = ~var, type = "scatter", mode = "lines", color = ~factor(month)) 

Created on 2023-02-05 with enter image description here

To answer you question with the lines: In ggplot when we use group = 1 like:

ggplot(d3, aes(x = date, y = var, group = 1, color = factor(month))) 
  geom_line()

We get: enter image description here

  • Related