C# winform 直线拟合示例带画图
时间: 2023-07-29 07:10:37 浏览: 230
C#Winform实例
以下是一个 C# WinForms 直线拟合示例程序,可以绘制数据点和拟合的直线:
```csharp
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace LinearRegressionExample
{
public partial class Form1 : Form
{
private List<double> xValues = new List<double>();
private List<double> yValues = new List<double>();
private double slope = 0;
private double intercept = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// 初始化绘图控件
chart1.Series.Clear();
chart1.Series.Add("Data");
chart1.Series.Add("Line");
chart1.Series["Data"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
chart1.Series["Line"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
chart1.Series["Line"].Color = Color.Red;
}
private void btnAddData_Click(object sender, EventArgs e)
{
double x, y;
if (!double.TryParse(txtX.Text, out x) || !double.TryParse(txtY.Text, out y))
{
MessageBox.Show("Invalid input!");
return;
}
xValues.Add(x);
yValues.Add(y);
chart1.Series["Data"].Points.Add(new DataPoint(x, y));
}
private void btnClearData_Click(object sender, EventArgs e)
{
xValues.Clear();
yValues.Clear();
chart1.Series["Data"].Points.Clear();
chart1.Series["Line"].Points.Clear();
}
private void btnFitLine_Click(object sender, EventArgs e)
{
if (xValues.Count != yValues.Count || xValues.Count < 2)
{
MessageBox.Show("Invalid data!");
return;
}
// 计算平均值
double xAvg = xValues.Average();
double yAvg = yValues.Average();
// 求斜率和截距
slope = xValues.Zip(yValues, (x, y) => (x - xAvg) * (y - yAvg)).Sum()
/ xValues.Zip(xValues, (x1, x2) => (x1 - xAvg) * (x2 - xAvg)).Sum();
intercept = yAvg - slope * xAvg;
// 绘制拟合直线
chart1.Series["Line"].Points.Clear();
chart1.Series["Line"].Points.Add(new DataPoint(xValues.Min(), slope * xValues.Min() + intercept));
chart1.Series["Line"].Points.Add(new DataPoint(xValues.Max(), slope * xValues.Max() + intercept));
}
private void chart1_PostPaint(object sender, ChartPaintEventArgs e)
{
// 绘制斜率和截距
if (xValues.Count > 0 && yValues.Count > 0)
{
Graphics g = e.ChartGraphics.Graphics;
g.DrawString($"y={slope:N2}x+{intercept:N2}", Font, Brushes.Black, new PointF(10, 10));
}
}
}
}
```
这个程序使用 `System.Windows.Forms.DataVisualization.Charting` 组件绘制图形,需要在项目中添加对该组件的引用。在窗体上放置一个 `Chart` 控件,以及一些按钮和文本框。用户可以在文本框中输入数据点,点击“Add Data”按钮添加到图表中;点击“Clear Data”按钮清除所有数据点;点击“Fit Line”按钮进行线性回归并绘制拟合的直线。拟合结果会显示在图表上。
阅读全文