简体   繁体   English

Plotly R订单图例条目

[英]Plotly R order legend entries

Is it possible to order the legend entries in R? 是否可以在R中订购图例条目?

If I eg specify a pie chart like this: 如果我例如指定一个这样的饼图:

  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))

The legend gets sorted by which Product has the highest number of Patients. 图例按哪个产品患者数最多排序。 I would like the legend to be sorted in alphabetical order by Product. 我希望图例按产品的字母顺序排序。

Is this possible? 这可能吗?

Yes, it's possible. 是的,这是可能的。 Chart options are here: https://plot.ly/r/reference/#pie . 图表选项在这里: https//plot.ly/r/reference/#pie

An example: 一个例子:

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))

Session info: 会话信息:

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

EDIT: Modified to work with plotly 4.xx (ie added ~ ) 编辑:修改为使用plotly 4.xx(即添加~

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

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