wpf二维数据拟合代码
时间: 2023-09-27 07:08:56 浏览: 153
以下是使用C#编写的WPF二维数据拟合代码:
1. 在XAML文件中添加一个Chart控件:
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<chartingToolkit:Chart Name="chart" Title="Data Fitting">
<chartingToolkit:Chart.Series>
<chartingToolkit:LineSeries Name="lineSeries" Title="Data Points" />
<chartingToolkit:LineSeries Name="lineSeriesFitted" Title="Fitted Curve" />
</chartingToolkit:Chart.Series>
<chartingToolkit:Chart.Axes>
<chartingToolkit:LinearAxis Orientation="X" Title="X Axis" />
<chartingToolkit:LinearAxis Orientation="Y" Title="Y Axis" />
</chartingToolkit:Chart.Axes>
</chartingToolkit:Chart>
</Grid>
</Window>
2. 在C#代码中添加以下方法:
using System.Windows.Controls.DataVisualization.Charting;
using System.Windows.Media;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Generate some random data points
double[] xValues = { 1, 2, 3, 4, 5 };
double[] yValues = { 2.2, 3.5, 4.1, 5.2, 6.7 };
// Add the data points to the chart
for (int i = 0; i < xValues.Length; i++)
{
lineSeries.Points.Add(new DataPoint(xValues[i], yValues[i]));
}
// Fit the data points to a line
double[] coefficients = FitLine(xValues, yValues);
double slope = coefficients[0];
double yIntercept = coefficients[1];
// Add the fitted curve to the chart
for (double x = 0; x < 6; x += 0.1)
{
double y = slope * x + yIntercept;
lineSeriesFitted.Points.Add(new DataPoint(x, y));
}
lineSeriesFitted.Stroke = Brushes.Red;
}
// Fit the data points to a line using least squares regression
private double[] FitLine(double[] xValues, double[] yValues)
{
double sumX = 0;
double sumY = 0;
double sumXY = 0;
double sumX2 = 0;
for (int i = 0; i < xValues.Length; i++)
{
sumX += xValues[i];
sumY += yValues[i];
sumXY += xValues[i] * yValues[i];
sumX2 += xValues[i] * xValues[i];
}
double slope = (xValues.Length * sumXY - sumX * sumY) / (xValues.Length * sumX2 - sumX * sumX);
double yIntercept = (sumY - slope * sumX) / xValues.Length;
return new double[] { slope, yIntercept };
}
}
3. 运行程序,即可看到数据点和拟合曲线的图形。
阅读全文