R Plotly:如何对饼图进行排序?

4
我在R中使用了plotly包来构建一个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))

你能为我们定义一下“数据”这个词吗? - Joy
谢谢@Joy。代码稍作修改,应该是df。 - Dendrobates
1个回答

8

好的,答案显然有两个方面。首先,在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))

在我的情况下,添加参数sort = FALSE是有效的。谢谢。 - Andrii

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接