首页 > 解决方案 > 如何在散点图上添加穿过原点(从正到负)的线 - highchart

问题描述

我正在尝试创建一条贯穿原点并从负向正传递的参考线。查看我正在尝试实现的示例 - 查看阈值线。此阈值线必须贯穿所有三个 x、y 坐标 (-1,-45,000)、(0.0)、(1, 45,000)。 在此处输入图像描述

以下是我到目前为止的工作。

http://jsfiddle.net/catio6/rhf6yre5/1/

我已经查看了这个以供参考,但是在尝试使用所有三个 x、y 坐标 (-1,-45,000)、(0.0)、(1, 45,000) 复制它几个小时后没有运气:http:/ /jsfiddle.net/phpdeveloperrahul/XvjfL/

$(function () {
    $('#container').highcharts({

        xAxis: {
            categories: ['Jan', 'Feb', 'Mar']
        },

        series: [{
            data: [29.9, 71.5, 256]
        }]

    }, function(chart) { // on complete
         console.log("chart = ");
        console.log(chart);
        //chart.renderer.path(['M', 0, 0, 'L', 100, 100, 200, 50, 300, 100])
        chart.renderer.path(['M', 75, 223.5,'L', 259, 47])//M 75 223.5 L 593 223.5
            .attr({
                'stroke-width': 2,
                stroke: 'red'
            })
            .add();

    });
});

标签: highcharts

解决方案


因此,据我所知,Highcharts 没有一种方法来定义一条从/到无穷大的线。我必须为您解决此问题的一个想法是根据您的数据动态计算线系列的值。这个想法很简单:给定要绘制的 X 和 Y 的最大值,我们只需要将轴限制为有意义的某个值并计算渐近线系列的值以使其看起来是无限的。我的算法如下所示:

// Get all your other data in a well formated way
let yourData = [
 {x: 0.57, y: 72484},
 {x: 0.57, y: 10000}
];

// Find which are the maximum x and y values
let maxX = yourData.reduce((max, v) => max > v.x ? max : v.x, -999999999);
let maxY = yourData.reduce((max, v) => max > v.y ? max : v.y, -999999999);

// Now you will limit you X and Y axis to a value that makes sense due the maximum values
// Here I will limit it to 10K above or lower on Y and 2 above or lower on X
let maxXAxis = maxX + 2;
let minXAxis = - (maxX + 2);
let maxYAxis = maxY + 10000;
let minYAxis = -(maxY + 10000);

// Now you need to calculate the values for the Willingness to pay series
let fn = (x) => 45000 * x; // This is the function that defines the Willingness to pay line

// Calculate the series values
let willingnessSeries = [];
for(let i = Math.floor(minXAxis); i <= Math.ceil(maxXAxis); i++) {
    willingnessSeries.push([i, fn(i)]);
}

这是一个工作小提琴:http: //jsfiddle.net/n5xg1970/

我为您的数据测试了几个值,所有这些值似乎都工作正常。希望对您有所帮助


推荐阅读