如何为负值绘制不同的渐变填充?

问题描述 投票:0回答:2

如何在正负区域都获得渐变填充,而不仅仅是纯色?

  • 正区域梯度应为蓝色
  • 负值梯度应为红色
  • 渐变色应在Y轴附近为黑色/透明(值0)

目标:https://codepen.io/francoisG/pen/gOOoEjQ

为了实现此目标,我不得不对第二个渐变停止点进行硬编码:

  • 正坡度:第二挡被迫至0.67
  • 负梯度:第二个挡块被迫至0.33

显然,这两个值不应该进行硬编码,因此无论数据如何,我如何都可以实时计算这两个值?每个值应为梯度部分相对于系列总范围的百分比。

  • 对于正梯度:(Ymax-0)/(Ymax-Ymin),在这种情况下为12/12 + 6 = 12/18 = 0.67
  • 对于负梯度:(0-Ymin)/(Ymax-Ymin),在此情况6/12 + 6 = 6/18 = 0.33

我的问题是我不知道如何在图表代码中计算这些数据。我用Ymin和Ymax尝试了很多事情,但没有成功。感谢您的帮助

series: [{
  name: 'John',
  data: [3, 4, -6, 5, 4, 10, 12],
  fillColor: {
    linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
    stops: [
      [0, Highcharts.getOptions().colors[0]],
      [0.67, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
    ]
  },
  zones: [{
    value: 0,
    color: '#D76363',
    fillColor: {
      linearGradient: {x1: 0, y1: 1, x2: 0, y2: 0},
      stops: [
        [0, 'rgba(215,99,99,0.5)'],
        [0.33, 'rgba(2,0,0,0)']
      ],
    }
  }]
javascript highcharts linear-gradients
2个回答
0
投票

您应该一起使用fillColornegativeFillColor并配置线性渐变样式。我在这里修改了您的代码:https://codepen.io/tredex/pen/yLLprxz

negativeFillColor: {
    linearGradient: {x1: 0, y1: 1, x2: 0, y2: 0},
    stops: [
      [0, '#D76363'],
      [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
    ]
},

fillColor: {
  linearGradient: {x1: 0, y1: 0, x2: 0, y2: 1},
  stops: [
    [0, Highcharts.getOptions().colors[0]],
    [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
  ]
}

0
投票

您可以使用chart.events.load回调函数和update()方法来设置这些计算值。查看下面的演示和代码:

chart: {
  renderTo: 'container',
  type: 'areaspline',
  events: {
    load: function() {
      const chart = this;
      const yAxis = chart.yAxis[0];

      let posGrad = (yAxis.max - 0) / (yAxis.max - yAxis.min);
      let negGrad = (0 - yAxis.min) / (yAxis.max - yAxis.min);

      chart.series[0].update({
        fillColor: {
          linearGradient: {
            x1: 0,
            y1: 0,
            x2: 0,
            y2: 1
          },
          stops: [
            [0, Highcharts.getOptions().colors[0]],
            [posGrad, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
          ]
        },
        zones: [{
          value: 0,
          color: '#D76363',
          fillColor: {
            linearGradient: {
              x1: 0,
              y1: 1,
              x2: 0,
              y2: 0
            },
            stops: [
              [0, 'rgba(215,99,99,0.5)'],
              [negGrad, 'rgba(2,0,0,0)']
            ],
          }
        }]
      });
    }
  }
}

Demo:

API参考:

© www.soinside.com 2019 - 2024. All rights reserved.