Search code examples
rplotlyr-plotly

Plotly R : Using colour and transformation with a line plot


I'm looking to filter by group (flower species) and the year (fake data I made). However, when i try do this the filtering breaks. This illustrated in the picture below where setosa is picked however there is virgincia data on the plot. It looks to be caused by using color =. I provided a solution to this problem, however, in my real example my mode = 'lines'. Which doesn't let me use this solution.

For context, my real example is a Duck curve graph. where the category is country and x-axis is hour of the day.

Reproducible example:

set.seed(42)
iris$year <- sample(2009:2011, 150, replace=TRUE) #MAKING FAKE YEAR DATA

p <- iris %>%
  plot_ly(
    type = 'scatter', 
    x = ~Sepal.Length, 
    y = ~Petal.Length,
    color = ~as.factor(year), # GROUPING BY YEAR
    ####### SAMPLE SOLUTION ######## comment out color =. and uncomment the below
    # marker = list(color = ~as.factor(year), size = 8, opacity = 0.8),
    text = ~Species, # ADDED THIS TO ILLUSTRATE THERE IS WRONG DATA IN THE TRANSFORMATION
    mode = 'markers', # IN MY REAL EXAMPLE IM USING LINES. 
    transforms = list(
      list(
        type = 'filter',
        target = ~Species,
        operation = '=',
        value = unique(iris$Species)[1]
      )
  )) %>% layout(
    updatemenus = list(
      list(
        type = 'dropdown',
        active = 0,
        buttons = list(
          list(method = "restyle",
               args = list("transforms[0].value", unique(iris$Species)[1]),
               label = unique(iris$Species)[1]),
          list(method = "restyle",
               args = list("transforms[0].value", unique(iris$Species)[2]),
               label = unique(iris$Species)[2]),
          list(method = "restyle",
               args = list("transforms[0].value", unique(iris$Species)[3]),
               label = unique(iris$Species)[3])
        )
      )
    )
  )

p

enter image description here

expected solution: mode = 'lines' & color by year while keeping the filtering of species. :)


Solution

  • Seems odd, but if you reorder your data.frame by your color variable first, your code works fine.

    set.seed(42)
    iris$year <- sample(2009:2011, 150, replace=TRUE) #MAKING FAKE YEAR DATA
    iris <- iris[order(iris$year), ]