简体   繁体   English

R Plotly:如何订购饼图?

[英]R Plotly: how to order pie chart?

I'm using the plotly package in R to build an R Shiny dashboard. 我正在R中使用plotly包来构建R Shiny仪表板。 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. 首先, plot_ly有一个参数,要求按值对数据进行排序(默认为TRUE )或使用自定义顺序。 Change this to FALSE . 将此更改为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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM