R Plotly:如何订购饼图?

R Plotly:如何订购饼图?,r,plotly,R,Plotly,我正在使用R中的plotly包构建一个R闪亮的仪表板。我想按自定义顺序(非字母顺序、非降序/升序)排列饼图。出于某种原因,我找不到如何实现这一点 非常感谢您的帮助 # Get Manufacturer mtcars$manuf <- sapply(strsplit(rownames(mtcars), " "), "[[", 1) df <- mtcars %>% group_by(manuf) %>% summarize(count = n()) # Crea

我正在使用R中的
plotly
包构建一个R闪亮的仪表板。我想按自定义顺序(非字母顺序、非降序/升序)排列饼图。出于某种原因,我找不到如何实现这一点

非常感谢您的帮助

# 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))
#找到制造商
mtcars$manuf%
汇总(计数=n())
#创建自定义订单
客户订单%
添加饼图(孔=0.6)%>%
布局(title=“使用Plotly的圆环图”,showlegend=F,
xaxis=list(showgrid=FALSE,zeroline=FALSE,showticklabels=FALSE),
yaxis=list(showgrid=FALSE,zeroline=FALSE,showticklabels=FALSE))

好的,答案显然是双重的。首先,
plot\u 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))
#找到制造商
mtcars$manuf%
汇总(计数=n())
#创建自定义订单
客户订单%
布局(title=“使用Plotly的圆环图”,showlegend=F,
xaxis=list(showgrid=FALSE,zeroline=FALSE,showticklabels=FALSE),
yaxis=list(showgrid=FALSE,zeroline=FALSE,showticklabels=FALSE))

你能给我们一个
数据的定义吗。对代码做了一点修改,应该是df。在我的例子中,添加参数sort=FALSE是有效的。谢谢