R Plotly:如何订购饼图? [英] R Plotly: how to order pie chart?
问题描述
我正在R中使用plotly
包来构建R Shiny仪表板.我想按自定义顺序(非字母顺序,非降序/升序)订购饼图.由于某种原因,我找不到实现该目标的方法.
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.
我们将不胜感激!
# 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))
推荐答案
好的,答案显然是双重的.首先,在plot_ly
中有一个参数,要求对数据进行排序(默认值为TRUE
)或使用自定义顺序.将其更改为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))
这篇关于R Plotly:如何订购饼图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!