Plotly R 排序图例项

7

有没有办法在R中对图例条目进行排序?

例如,如果我像这样指定一个饼图:

  plot_ly(df, labels = Product, values = Patients, type = "pie",
          marker = list(colors = Color), textfont=list(color = "white")) %>%
    layout(legend = list(x = 1, y = 0.5))

传说根据具有最高患者数量的产品进行排序。我希望传说按产品名称字母顺序排序。
这是否可能?
1个回答

11

是的,这是可能的。图表选项在这里:https://plot.ly/r/reference/#pie

一个例子:

library(plotly)
library(dplyr)

# Dummy data
df <- data.frame(Product = c('Kramer', 'George', 'Jerry', 'Elaine', 'Newman'), 
                 Patients = c(3, 6, 4, 2, 7))

# Make alphabetical
df <- df %>%
    arrange(Product)

# Sorts legend largest to smallest
plot_ly(df, 
        labels = ~Product, 
        values = ~Patients, 
        type = "pie",
        textfont = list(color = "white")) %>%
    layout(legend = list(x = 1, y = 0.5))

# Set sort argument to FALSE and now orders like the data frame
plot_ly(df, 
        labels = ~Product, 
        values = ~Patients, 
        type = "pie",
        sort = FALSE,
        textfont = list(color = "white")) %>%
    layout(legend = list(x = 1, y = 0.5))

# I prefer clockwise
plot_ly(df, 
        labels = ~Product, 
        values = ~Patients, 
        type = "pie",
        sort = FALSE,
        direction = "clockwise",
        textfont = list(color = "white")) %>%
    layout(legend = list(x = 1, y = 0.5))

会话信息:

R version 3.5.0 (2018-04-23)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_Australia.1252  LC_CTYPE=English_Australia.1252    LC_MONETARY=English_Australia.1252 LC_NUMERIC=C                       LC_TIME=English_Australia.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] bindrcpp_0.2.2 dplyr_0.7.5    plotly_4.7.1   ggplot2_2.2.1

编辑:

为了与plotly 4.x.x兼容(即添加~),已进行修改。


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