You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Plotly中手动排序IMDb Top250电影评级饼图标签?

手动调整Plotly饼图的标签排序

问题描述

想要制作IMDb Top250电影按评级/证书统计数量的饼图,已创建指定顺序的向量并将certificate转为因子排序,但Plotly始终不按设定的标签顺序展示。

用户原始代码

x <- c('G', 'PG', 'PG-13', 'R', 'Not Rated', 'Other')

Ratings_df <- df %>%
  dplyr::group_by(certificate) %>%
  dplyr::summarize(count = n()) %>%
  dplyr::mutate(certificate = ifelse(count < 17, "Other", certificate)) %>%
  dplyr::group_by(certificate) %>%
  dplyr::summarise(count = sum(count)) %>%
  dplyr::mutate(certificate = factor(certificate, levels = x)) %>%
  dplyr::arrange(certificate) %>%
  data.frame()
Ratings_df

plot_ly(Ratings_df, labels = ~certificate, values = ~count) %>%
  add_pie(hole=0.6) %>%
  layout(xaxis = list(categoryorder = "array", 
                      categoryarray = c('G', 'PG', 'PG-13', 'R', 'Not Rated', 'Other')),
    title="Count of Films by Rating")

解决方案

Plotly饼图的排序逻辑和轴类图表不同,layout里的xaxis设置对饼图无效,要手动控制标签顺序只需两步:

  1. 确认数据框行顺序符合需求:你已经通过factor定义层级+arrange排序完成了这一步,Ratings_df的行已经按x的顺序排列,这部分无需修改。
  2. 在add_pie中添加sort = FALSE参数:Plotly默认会按数值大小排序饼图切片,设置该参数后,会严格遵循数据框的行顺序渲染标签和切片。

修改后的绘图代码:

plot_ly(Ratings_df, labels = ~certificate, values = ~count) %>%
  add_pie(hole = 0.6, sort = FALSE) %>%  # 关键:禁用自动排序
  layout(title = "Count of Films by Rating")

这样就能让饼图标签严格按照['G', 'PG', 'PG-13', 'R', 'Not Rated', 'Other']的顺序展示。

内容的提问来源于stack exchange,提问作者TWilliams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 09:31:03