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

R语言Plotly柱状图X轴顺序设置及Y轴刻度匹配问题求助

纯Plotly解决方案:按平均深度排序净度类别的柱状图

我帮你梳理下当前代码的核心问题,然后给出正确的实现方式:

问题分析

  1. 未指定柱状图类型:你没有设置type = "bar",Plotly默认绘制散点图,再加上用mutate保留了1000行重复数据(每个净度组下的所有行都带相同的平均深度值),这不仅让图表显示异常,还导致Y轴范围被错误计算(出现0-16000的不合理范围)。
  2. 数据未正确聚合:要绘制分组均值的柱状图,应该用summarise只保留每个净度组的一行均值数据,而不是mutate给每一行都添加均值。

正确代码实现(两种方式可选)

方式1:提前排序数据集(更直观)

这种方式先对聚合后的均值数据按平均深度升序排序,Plotly会自动沿用这个顺序渲染X轴:

library(tidyverse)
library(plotly)
set.seed(321)

# 1. 取子集并聚合计算每个净度的平均深度,同时按均值升序排序
my_diamonds <- ggplot2::diamonds %>% 
  slice(sample(nrow(.), 1000)) %>%
  group_by(clarity) %>%
  summarise(mean_depth = mean(depth), .groups = "drop") %>%
  arrange(mean_depth)  # 按平均深度升序排序

# 2. 绘制Plotly柱状图
plot_ly(data = my_diamonds,
        x = ~clarity,
        y = ~mean_depth,
        type = "bar",
        # 自定义悬停提示,让信息更清晰
        hovertemplate = "净度: %{x}<br>平均深度: %{y:.2f}<extra></extra>") %>%
  layout(title = "Mean Depth for each Clarity Category",
         xaxis = list(title = "净度"),
         yaxis = list(title = "平均深度"))

方式2:通过X轴参数指定排序(无需提前排序数据集)

如果你不想修改数据集顺序,可以直接在layout中用categoryorder和categoryarray指定排序规则:

library(tidyverse)
library(plotly)
set.seed(321)

# 1. 取子集并聚合计算每个净度的平均深度
my_diamonds <- ggplot2::diamonds %>% 
  slice(sample(nrow(.), 1000)) %>%
  group_by(clarity) %>%
  summarise(mean_depth = mean(depth), .groups = "drop")

# 2. 绘制Plotly柱状图,显式指定X轴排序规则
plot_ly(data = my_diamonds,
        x = ~clarity,
        y = ~mean_depth,
        type = "bar") %>%
  layout(title = "Mean Depth for each Clarity Category",
         xaxis = list(
           categoryorder = "array",
           # 用reorder生成按平均深度升序排列的净度数组
           categoryarray = ~reorder(clarity, mean_depth),
           title = "净度"
         ),
         yaxis = list(title = "平均深度"))

效果说明

运行上述代码后,你会看到:

  • Y轴范围自动适配平均深度的实际值(61-62左右),不再出现0-16000的异常情况
  • X轴的净度类别会严格按照对应组的平均深度升序排列
  • 悬停提示显示的数值与柱状图高度完全匹配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 09:12:36