我编写了一个程序,根据用户的几个输入值计算最佳拟合线(截距/斜率)。我已经绘制了每个单独的值,但不确定代码是否为绘制线给定斜率和y截距。
这是斜率:
double m = ( aXY.Sum() -
((levels.Sum() * scores.Sum()) / 5)) / (newaX.Sum() - ((powLevels) / 5));
拦截
double b = meanY - (m * meanX);
绘制积分
for (int i = 0; i < levels.GetLength(0); i++)
{
chart1.Series["Series1"].Points
.AddXY(levels.GetValue(i), scores.ToArray().GetValue(i));
}
有什么想法吗?我绝不是一位专家,而且这个方面需要进行一些实验......
答案 0 :(得分:0)
假设您使用ChartType.Points
将数据绘制为散点图,最简单的添加行的方法是在Series
添加一个额外 ChartType.Line
并设置那里有两点。
是在Chart
上创建一条线的其他方法,例如绘制它或创建LineAnnotation
,但它们多更多复杂!
在this example 之后,这是一个实现:
请注意,在为最适合的行创建系列后,您要查找的内容只是最后两行 ..:
private void button1_Click(object sender, EventArgs e)
{
// create TWO series!
chart1.Series.Clear();
chart1.Series.Add("Data");
chart1.Series.Add("Line of best fit");
chart1.Series[0].ChartType = SeriesChartType.Point;
chart1.Series[1].ChartType = SeriesChartType.Line;
List<int> levels = new List<int>() { 8, 2, 11, 6, 5, 4, 12, 9, 6, 1};
List<int> scores = new List<int>() { 3, 10, 3, 6, 8, 12, 1, 4, 9, 14};
double minX = levels.ToList().Min();
double maxX = levels.ToList().Max();
double meanX = 1f * levels.Sum() / levels.Count;
double meanY = 1f * scores.Sum() / scores.Count;
double st = 0;
double sb = 0;
for (int i = 0; i < levels.Count; i++ )
{
st += (levels[i] - meanX) * (scores[i] - meanY);
sb += (levels[i] - meanX) * (levels[i] - meanX);
}
double slope = st / sb;
double y0 = meanY - slope * meanX; // y-intercept or y-crossing
for (int i = 0; i < levels.Count; i++)
{
chart1.Series[0].Points.AddXY(levels[i], scores[i]);
}
// this is the part that creates the line of best fit:
chart1.Series[1].Points.AddXY(minX, y0 + minX * slope);
chart1.Series[1].Points.AddXY(maxX, y0 + maxX * slope);
}
如果您愿意,可以在y轴上添加第一个直线点:
chart1.Series[1].Points.AddXY(0, y0 );
在这种情况下,您可能需要设置图表中显示的最小x值,以防止它包含-1
,可能是这样的:
chart1.ChartAreas[0].AxisX.Minimum = minX - 1;