【问题标题】:Make x axis values the same as series使 x 轴值与系列相同
【发布时间】:2020-09-20 16:37:23
【问题描述】:

是否可以仅在 x 轴上显示系列数据? 比如我有serie:

"data":[{"x":70000,"y":6.5354E7}, {{"x":71000,"y":5.5354E7}} ....]

我只想在 x 轴上提供 x 值。在默认设置下,轴上的值甚至有分数。

我尝试使用不同的选项,但没有任何成功。

【问题讨论】:

    标签: apexcharts


    【解决方案1】:

    您可以使用类别来完全控制 X 轴标签中显示的值。官方文档中有很多带有文本标签的示例,但也没有什么可以阻止您使用数字。它们只是标签。

    而不是:

    let options = {
      series: [
        {
          data: [{"x":70000,"y":6.5354E7}, {"x":71000,"y":5.5354E7}]
        }
      ]
      ...
    };
    

    你会:

    let options = {
      series: [
        {
          data: [{"x":1,"y":6.5354E7}, {"x":2, "y":5.5354E7}]
        }
      ],
      xaxis: {
        categories: [70000, 71000]
      }
      ...
    };
    

    您可以通过迭代每个点并将每个唯一的 x 值存储到数组中来自动执行此操作。下面是一个例子:

    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    
    <div id="chart"></div>
    
    <script>
    function createCategories(series) {
      let unique = new Set();
    
      // Collects unique x coordinates.
      for (let serie of series) {
        for (let point of serie.data) {
          unique.add(point.x);
        }
      }
    
    
      // Creates categories
      let categories = Array.from(unique);
    
      // Sorts categories ascendantly.
      categories.sort((a, b) => a - b);
    
      return categories;
    }
    
    function replaceXCoordinatesWithCategories(series, categories) {
      for (let serie of series) {
        for (let point of serie.data) {
          point.x = categories.indexOf(point.x) + 1;
        }
      }
    }
    
    let series = [
      {
        data: [
          { x: 71000, y: 3.5354E7 },
          { x: 72000, y: 2.5354E7 },
          { x: 73000, y: 1.5354E7 },
          { x: 74000, y: 5.5354E7 },
          { x: 75000, y: 4.5354E7 },
          { x: 76000, y: 4.5354E7 },
        ]
      },
      {
        data: [
          { x: 71000, y: 6.5354E7 },
          { x: 72000, y: 5.5354E7 },
          { x: 73000, y: 4.5354E7 },
          { x: 74000, y: 3.5354E7 },
          { x: 75000, y: 2.5354E7 },
        ]
      }
    ];
    
    let categories = createCategories(series);
    replaceXCoordinatesWithCategories(series, categories);
    
    let options = {
      series: series,
      chart: {
        height: 350,
        type: 'line'
      },
      xaxis: {
        categories: categories
      }
    };
    
    let chart = new ApexCharts(document.querySelector("#chart"), options);
    chart.render();
    </script>

    【讨论】:

    • 我绑定了你的方法,它有效,但数据更新完全破坏了它:((我在接收数据后计算新类别,但是当我更新选项时,XAxis 显示 X 条目(1、2、 3) 就好像它从类别模式恢复一样。
    猜你喜欢
    • 2020-12-17
    • 1970-01-01
    • 2011-09-28
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多