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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With