R Plotly:如何订购饼图?

Den*_*tes 3 r plotly

我正在plotlyR中使用该软件包来构建R Shiny仪表板。我想按自定义顺序(非字母顺序,非降序/升序)订购饼图。由于某些原因,我找不到实现该目标的方法。

帮助将不胜感激!

# 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))
Run Code Online (Sandbox Code Playgroud)

Den*_*tes 5

好的,答案显然是双重的。首先,中有一个参数plot_ly,要求按值对数据进行排序(默认为TRUE)或使用自定义顺序。将此更改为FALSE

然后,其次,顺序(顺时针)不同于数据帧中的顺序。饼图从右上角开始,然后逆时针继续。

因此,以下解决了该问题:

# 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))
Run Code Online (Sandbox Code Playgroud)