首页 > 解决方案 > 仅在图表 highcharts 上显示第一个和最后一个 y 轴标签

问题描述

对于图表,我只想显示属于第一个值和最后一个值的标签。

我试图通过事件触发器获取最后一个值。不幸的是,这只适用于最后一个值,而不是第一个值。我也不知道如何为这两个系列做到这一点。到目前为止,我只管理系列 [0]。

  chart: {
    type: 'line',
    events: {
      load: function() {
        var chart = this,
          points = chart.series[0].points,
          lastValue,
          chosenPointlast;

        points.forEach(function(point, index) {
          if (!lastValue || lastValue < point.x) {
            lastValue = point.x;
            chosenPointlast = point;
          }
        }); 

        chosenPointlast.update({
          marker: {
            enabled: true,
            fillColor: 'orange'
          },
          dataLabels: {
            enabled: true,
            color: 'orange'
          },
        });
      }
    }
  },
  title: {
    text: 'Monthly Average Temperature'
  },
  subtitle: {
    text: 'Source: WorldClimate.com'
  },
  xAxis: {
    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  },
  yAxis: {
    title: {
      text: 'Temperature (°C)'
    }
  },
  plotOptions: {
    line: {
      dataLabels: {
        enabled: false
      },
      enableMouseTracking: false
    }
  },
  series: [{
    name: 'Tokyo',
    data: [7.0, 6.9, 9.5, 14.5, 18.4, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
  }, {
    name: 'London',
    data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]
  }]
});

所以我希望看到系列 [0] 的标签为 7.0 和 9.6,系列 [1] 的标签为 3.9 和 4.8。希望你能帮助我。JSFiddle

标签: javascripthighchartslabel

解决方案


您可以通过这种方式找到一个系列的4个边缘点:

const pointsSortedByY = serie.points.sort((p1, p2) => p2.y - p1.y);
const top = pointsSortedByY[0];
const bottom = pointsSortedByY[pointsSortedByY.length - 1];

const pointsSortedByX = serie.points.sort((p1, p2) => p2.x - p1.x);
const first = pointsSortedByX[0];
const last = pointsSortedByX[pointsSortedByX.length - 1];

然后你可以打印它:

[top,bottom, first, last].forEach(function (point) {
    point.update({
        marker: {
            enabled: true,
            fillColor: 'green'
        },
        dataLabels: {
            enabled: true,
            color: 'green'
        }
    });
},this);

最后对每个系列重复相同的操作:

chart1.series.forEach(function (serie) {
    printTopAndBottom(serie);
}, this);

这是结果: 结果

https://jsfiddle.net/7ue8ow0b/


推荐阅读