java散点图拟合曲线输出曲线公式
时间: 2024-02-20 16:49:15 浏览: 87
可以使用Java的第三方库JFreeChart来实现散点图拟合曲线输出曲线公式。具体步骤如下:
1. 导入JFreeChart库。
2. 创建一个XYDataset对象,用来存放散点数据。
3. 使用JFreeChart提供的函数来创建一个散点图。
4. 使用JFreeChart提供的函数来给散点图添加拟合曲线。
5. 通过拟合曲线的系数计算出曲线公式。
下面是一个简单的示例代码:
```java
import java.awt.Color;
import java.awt.Font;
import java.text.DecimalFormat;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.function.Function2D;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
public class ScatterPlotDemo extends ApplicationFrame {
public ScatterPlotDemo(String title) {
super(title);
}
public static void main(String[] args) {
double[][] data = new double[][]{{1, 2}, {2, 4}, {3, 6}, {4, 8}, {5, 10}}; //散点数据
XYDataset dataset = DatasetUtilities.createScatterPlotDataset("Scatter Plot", data); //创建XYDataset对象
JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot", "X", "Y", dataset, PlotOrientation.VERTICAL, true, true, false); //创建散点图
XYPlot plot = (XYPlot) chart.getPlot();
plot.setBackgroundPaint(Color.white);
plot.setDomainGridlinePaint(Color.black);
plot.setRangeGridlinePaint(Color.black);
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
plot.setRenderer(new XYLineAndShapeRenderer(true, false)); //添加拟合曲线
Function2D curve = DatasetUtilities.createPolyFitFunction2D(dataset, 2); //拟合曲线的阶数为2
plot.setDataset(1, DatasetUtilities.sampleFunction2D(curve, 1, 5, 100, "Fitted Curve"));
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
renderer.setSeriesPaint(0, Color.red);
plot.setRenderer(1, renderer);
NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
domainAxis.setAutoRangeIncludesZero(false);
domainAxis.setTickMarkInsideLength(2.0f);
domainAxis.setTickMarkOutsideLength(2.0f);
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setTickMarkInsideLength(2.0f);
rangeAxis.setTickMarkOutsideLength(2.0f);
rangeAxis.setNumberFormatOverride(new DecimalFormat("0.000"));
chart.getLegend().setItemFont(new Font("Arial", Font.PLAIN, 12));
chart.getTitle().setFont(new Font("Arial", Font.BOLD, 14));
ScatterPlotDemo demo = new ScatterPlotDemo("Scatter Plot Demo");
demo.pack();
demo.setVisible(true);
System.out.println("拟合曲线公式为:" + curve.toString()); //输出拟合曲线公式
}
}
```
上述代码中使用了createPolyFitFunction2D函数来创建拟合曲线,该函数的第二个参数为拟合曲线的阶数。在最后一行代码中,输出了拟合曲线的公式。
阅读全文