Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Plotly: how to order pie chart?

Tags:

r

plotly

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). For some reason I can't find how to achieve this.

Help would be highly appreciated!

# 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])

# 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) %>%
  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))
like image 804
Dendrobates Avatar asked Mar 09 '23 01:03

Dendrobates


1 Answers

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))
like image 161
Dendrobates Avatar answered Mar 28 '23 15:03

Dendrobates