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

如何将React Apex Charts水平条形图默认排序改为降序

如何将React Apex-Charts水平条形图设置为降序排列

你当前的水平条形图按数据升序排列(数值小的条形在顶部),要改成降序(数值大的条形在顶部),有两种简单实现方式:

方法1:手动排序数据与分类(更可控)

series.data和xaxis.categories是一一对应的,你可以将两者组合成对象数组,按数值降序排序后拆分回原结构:

// 组合数据与分类,补全原代码中缺失的对应关系
const sortedData = [
  { value: 4000, school: "Jomo Kenyatta Univerity" },
  { value: 4300, school: "Technical Univaersity of Kenya" },
  { value: 4408, school: "University of Nairobi" },
  { value: 4700, school: "Kenyatta University" },
  { value: 5400, school: "Moi University" },
  { value: 5800, school: "Masinde Muliro University" },
  { value: 6900, school: "Maasai Mara University" },
  { value: 11000, school: "Maseno University" },
  { value: 12000, school: "Laikipia University" },
  { value: 13800, school: "补充缺失的学校名称" } // 原data有10个值,categories少1个,需补全
].sort((a, b) => b.value - a.value); // 降序排序

// 拆分回data和categories数组
const chartData = sortedData.map(item => item.value);
const chartCategories = sortedData.map(item => item.school);

在Chart组件中使用处理后的数组:

<Chart
  type='bar'
  height={550}
  series={[{
    name: "Transaction",
    data: chartData,
  }]}
  options={{
    title:{ text:"Top 10 Schools By Transactions", style: { fontSize: 25 , fontFamily: "IBM Plex Sans", fontWeight:700} },
    colors: ["#295fab"],
    yaxis: {
      labels: {
        formatter: (val) => `${val}`,
        style: {fontWeight:500, fontSize: "15", colors: ["#000"], fontFamily:"IBM Plex Sans" },
      },
    },        
    xaxis: {
      categories: chartCategories, // 替换为排序后的分类
      labels:{
        formatter: (val) => `$${val}`,
        style: {fontSize: "14",fontWeight:500, colors: ["#000"], fontFamily:"IBM Plex Sans" },
      }
    },
    noData: { text: "Loading..." },
    chart: {
      fontFamily: 'IBM Plex Sans',
      toolbar: {
        tools: {
          download: true,
          selection: false,
          zoom: false,
          zoomin: false,
          zoomout: false,
          pan: false,
          reset: false,
          customIcons: []
        },
      },
    },
    dataLabels: {
      enabled: true,
      formatter: (val) => `$${val}`,
      offsetX: 40,
      style: { fontSize: '12px', colors: ["#304758"] },
    },
    plotOptions: {
      bar: {
        borderRadius: 16,
        horizontal: true,
        dataLabels: { position: 'top' },
      }
    },
    legend:{ fontSize: "16px", fontFamily: "IBM Plex Sans" }
  }}
/>

方法2:使用ApexCharts内置排序配置

直接在plotOptions.bar中添加sort: 'desc',让图表自动按数值降序排列:

plotOptions: {
  bar: {
    borderRadius: 16,
    horizontal: true,
    dataLabels: { position: 'top' },
    sort: 'desc' // 新增降序配置
  }
},

该方法更简洁,要求ApexCharts版本在v3.0及以上。

重要提示

原代码中xaxis.categories只有9个元素,而series.data有10个值,两者数量不匹配会导致图表显示异常,需要补全对应关系。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:41:29