plotly / plotly.R

An interactive graphing library for R
https://plotly-r.com
Other
2.53k stars 622 forks source link

Adding 'name' parameter to plot_ly() function removes factor ordering. #1064

Open Mkkl91 opened 7 years ago

Mkkl91 commented 7 years ago

We sometimes use the 'name' parameter within the plot_ly() function to add a suffix to the values shown in a legend. Values in the legend are shown because a variable (legend variable) is used for the 'color' parameter in plot_ly().

Since a few days/weeks, using this method to add a suffix leads to the ordering of 'legend variable' to switch to alphabetical order instead of its original factor levels.

I added an example below.

library(plotly)
library(lubridate)

factor <- factor(x = c('bbb', 'ccc', 'aaa'), levels = c('bbb', 'ccc', 'aaa'))
number <- c(1,2,3)
date <- c(ymd(20170101), ymd(20170202), ymd(20170303))

levels(factor)

df <- data.frame(letter = factor, number = number, date = date)

levels(df$letter)

plot_ly(df, x = ~number, y = ~date, type = 'bar', color = ~letter)
plot_ly(df, x = ~number, y = ~date, type = 'bar', color = ~letter, name = 'ff')
plot_ly(df, x = ~number, y = ~date, type = 'bar', color = ~letter, name = c('asd', 'ff', 'ss'))
cpsievert commented 7 years ago

For now you can use style() to alter the default naming, for example:

plot_ly(df, x = ~number, y = ~date, type = 'bar', color = ~letter) %>% 
  style(name = "foo", traces = 1)
nienkeg commented 6 years ago

Is there a way to set the names of all the traces using only one style function? I tried using the following code, but it's not working:

plot_ly(df, x = ~number, y = ~date, type = 'bar', color = ~letter) %>% style(name = c("foo", "test1", "test2"), traces = c(1:3))

cpsievert commented 5 years ago

You'll have to make multiple calls to style():

plot_ly(df, x = ~number, y = ~date, type = 'bar', color = ~letter) %>% 
  style(name ="foo", traces = 1) %>%
  style(name ="test1", traces = 2) %>%
  style(name ="test2", traces = 3)