Michael Szczepaniak
Michael Szczepaniak

Reputation: 2110

Plotly R order scatter plot legend entries

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).

Upvotes: 4

Views: 4672

Answers (2)

GValER
GValER

Reputation: 47

To add something to previous answer, you can also choose colors for names. Note I added Peter to show that if whenever it appears Peter (not this case), its color would be gray (I needed to choose colors in shiny and I needed them to be the same, whether they appeared or not, or in casi they appear)

dat$f_name <- factor(dat$f_name, levels = c("Jane", "Fred", "Sally", "Peter"))
ccolors <- c('black', 'blue','red', 'gray')

plot_ly(dat, x=~date, y=~y1, color=~f_name, colors=ccolors,
    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)

Upvotes: 1

Tung
Tung

Reputation: 28391

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

Upvotes: 7

Related Questions