R Plotly: how to order pie chart?

前端 未结 1 1248
-上瘾入骨i
-上瘾入骨i 2021-01-19 18:56

I\'m using the plotly package in R to build an R Shiny dashboard. I want to order my pie chart in a custom order (non-alphabetic, non-descending/ascending order

相关标签:
1条回答
  • 2021-01-19 19:17

    Ok, the answer is apparently twofold. Firstly, there is an argument in plot_ly, asking to sort the data on values (default is TRUE) or work with the custom order. Change this to FALSE.

    Then, secondly, the order (clockwise) is different from the order in the data frame. The pie starts in the top right corner, and continues counterclockwise.

    Hence, the following solves the problem:

    # Get Manufacturer
    mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1)
    
    df <- mtcars %>%
      group_by(manuf) %>%
      summarize(count = n())
    
    # Create custom order
    customOrder <- c(df$manuf[12:22],df$manuf[1:11])
    
    # Adjust customOrder to deal with pie
    customOrder <- c(customOrder[1],rev(customOrder[2:length(customOrder)]))
    
    # Order data frame
    df <- df %>% slice(match(customOrder, manuf))
    
    # Create factor
    df$manuf <- factor(df$manuf, levels = df[["manuf"]])
    
    # Plot
    df %>% plot_ly(labels = ~manuf, values = ~count, sort = FALSE) %>%
      add_pie(hole = 0.6) %>%
      layout(title = "Donut charts using Plotly",  showlegend = F,
             xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
             yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
    
    0 讨论(0)
提交回复
热议问题