R Plotly: how to order a pie chart?

I am using a package plotly

in R to create an R Shiny toolbar. I want to order my pie chart in a custom order (no alphabet, no descending / ascending order). For some reason, I can't seem to find how to achieve this.

Help would be much 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))

      

+3


source to share


1 answer


Okay, the answer seems to be twofold. First, plot_ly

there is an argument that asks you to sort the data by value (default - TRUE

) or work with a custom order. Change this to FALSE

.

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



Hence the following solution to 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))

      

+3


source







All Articles