我需要在代码中复制这个Excel图表
给定[x,y]值列表,如何获取新的值列表以绘制功率趋势线?
我发现有人提到这个http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html公式。但是不知道如何从中生成新的值列表。
答案 0 :(得分:1)
按照链接中的公式:
function getFittedPoints(data) {
var log = Math.log,
pow = Math.pow,
sums = [
0, // sum of the logarithms of x ( sum(log(x)) )
0, // sum of the logarithms of y ( sum(log(y)) )
0, // sum of the logarithms of the products of x and y ( sum(log(x) * log(y)) )
0 // sum of the powers of the logarithms of x ( sum((log(x))^2 )
],
fittedPoints = [], // return fitted points
a, // a coefficient
b, // b coefficient
dataLen = data.length,
i,
logX,
logY;
for (i = 0; i < dataLen; i++) {
sums[0] += logX = log(data[i][0]);
sums[1] += logY = log(data[i][1]);
sums[2] += logX * logY;
sums[3] += pow(logX, 2);
}
b = (i * sums[2] - sums[0] * sums[1]) / (i * sums[3] - pow(sums[0], 2));
a = pow(Math.E, (sums[1] - b * sums[0]) / i);
for (i = 0; i < dataLen; i++) {
fittedPoints.push([
data[i][0],
a * pow(data[i][0], b)
]);
}
return fittedPoints;
}
然后将该函数应用于数据。
示例:http://jsfiddle.net/fa3m4Lvf/
当然,如果您的数据不干净,那么您可以通过处理空值等来改进功能
答案 1 :(得分:1)
对于那些正在寻找上述摩根免费答案的C#版本的人来说,这里有翻译:
public static IEnumerable<double> GetPowerTrendline(IList<double> knownY, IList<double> knownX, IList<double> newX)
{
var sums = new double[4];
var trendlinePoints = new List<double>();
var dataLen = knownX.Count;
for (var i = 0; i < dataLen; i++)
{
var logX = Math.Log(knownX[i]);
var logY = Math.Log(knownY[i]);
sums[0] += logX;
sums[1] += logY;
sums[2] += logX * logY;
sums[3] += Math.Pow(logX, 2);
}
var b = (dataLen * sums[2] - sums[0] * sums[1]) / (dataLen * sums[3] - Math.Pow(sums[0], 2));
var a = Math.Pow(Math.E, (sums[1] - b * sums[0]) / dataLen);
foreach (var x in newX)
{
var pointY = a * Math.Pow(x, b);
trendlinePoints.Add(pointY);
}
return trendlinePoints;
}
请注意,它会被修改,以便获取所需x点的列表,而不是使用提供的x点。
答案 2 :(得分:0)
我遵循以下示例计算:DEMO
基于此修改了Adams示例,并为此C#解决方案提供了帮助。假设您拥有所有现有的散点图。结果是一些arraylists,其中包含trendline的所有x和y值,您可以直接将其插入到highcharts中。
series: [
{
type: 'line',
name: 'Trendlinje',
data: data.RegressionLine,
color: '#444444',
marker: {
enabled: false
},
states: {
hover: {
lineWidth: 0
}
},
enableMouseTracking: false
},
在我的HighCharts方法中这样:
chartData(GraphData.year, GraphData.month, GraphData.day, GraphData.hour, GraphData.minute, GraphData.y, GraphData.indexLabel, GraphData.markerColor, GraphData.markerType))