marcopah marcopah - 2 months ago 14
R Question

Plotly R order legend entries

Is it possible to order the legend entries in R?

If I e.g. specify a pie chart like this:

plot_ly(df, labels = Product, values = Patients, type = "pie",
marker = list(colors = Color), textfont=list(color = "white")) %>%
layout(legend = list(x = 1, y = 0.5))


The legend gets sorted by which Product has the highest number of Patients. I would like the legend to be sorted in alphabetical order by Product.

Is this possible?

mal mal
Answer

Yes, it's possible. Chart options are here: https://plot.ly/r/reference/#pie.

An example:

library(plotly)
library(dplyr)

# Dummy data
df <- data.frame(Product = c('Kramer', 'George', 'Jerry', 'Elaine', 'Newman'), 
                 Patients = c(3, 6, 4, 2, 7))

# Make alphabetical
df <- df %>%
    arrange(Product)

# Sorts legend largest to smallest
plot_ly(df, 
        labels = Product, 
        values = Patients, 
        type = "pie",
        textfont = list(color = "white")) %>%
    layout(legend = list(x = 1, y = 0.5))

# Set sort argument to FALSE and now orders like the data frame
plot_ly(df, 
        labels = Product, 
        values = Patients, 
        type = "pie",
        sort = FALSE,
        textfont = list(color = "white")) %>%
    layout(legend = list(x = 1, y = 0.5))

# I prefer clockwise
plot_ly(df, 
        labels = Product, 
        values = Patients, 
        type = "pie",
        sort = FALSE,
        direction = "clockwise",
        textfont = list(color = "white")) %>%
    layout(legend = list(x = 1, y = 0.5))

Session info:

R version 3.2.3 (2015-12-10)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows >= 8 x64 (build 9200)

...

attached base packages:
[1] stats     graphics  grDevices utils     datasets 
[6] methods   base     

other attached packages:
[1] dplyr_0.4.3   plotly_3.4.3  ggplot2_2.1.0

EDIT: This example uses plotly 3.x.x. If you use plotly 4.x.x or above, this code may not work as is. See here for more details: https://www.r-bloggers.com/upgrading-to-plotly-4-0-and-above/

Comments