Plotly R order scatter plot legend entries

Michael Szczepaniak

I create a plot in the following manner:

## generate test data
getTestData <- function(seed_val=711, noise=1.0) {
    set.seed(seed_val)
    d <- seq(as.Date('2017/01/01'), as.Date('2017/01/08'), "days")
    first_name <- rep("Jane", 8)
    first_name <- append(first_name, rep("Fred", 8))
    first_name <- append(first_name, rep("Sally", 8))
    y1_vals <- seq(1, 3*8, 1)
    y2_vals <- rnorm(3*8, mean=y1_vals, sd=noise)
    dat <- data.frame(date=d, f_name=first_name, y1=y1_vals, y2=y2_vals,
                  stringsAsFactors = FALSE)
    return(dat)
}

dat <- getTestData()
library(dplyr)
library(plotly)
p1 <- plot_ly(dat, x=~date, y=~y1, color=~f_name,
              type = 'scatter', mode = "lines+markers") %>% 
    layout(yaxis = list(title = "some important y value")) %>% 
    add_trace(y=~y2, name='actual', showlegend=FALSE, 
              type='scatter', mode='lines',
              line=list(width = 2, dash = 'dash'), color=~f_name)

enter image description here

Plotly orders the legend alphabetically by the f_name grouping, but I want this order to be: Jane, Fred, Sally which is the original order in the data frame

The accepted answer given here:

Plotly R order legend entries

in the section commented as #Set sort argument to FALSE and now orders like the data frame is very close to what I need, but this solution is for a pie chart. I need to reorder my legend in a scatterplot which doesn't appear to have a sort parameter available to set (like the pie chart does).

Tung

Is this what you want?

dat$f_name <- factor(dat$f_name, levels = c("Jane", "Fred", "Sally"))

plot_ly(dat, x=~date, y=~y1, color=~f_name,
    type = 'scatter', mode = "lines+markers") %>% 
        layout(yaxis = list(title = "some important y value")) %>% 
        add_trace(y=~y2, name='actual', showlegend=FALSE, 
          type='scatter', mode='lines',
          line=list(width = 2, dash = 'dash'), color=~f_name)

enter image description here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related