JFreechart绘制2D散点图

JFreechart绘制2D散点图

觉得有用的话,欢迎一起讨论相互学习~


我的微博我的github我的B站

  • JFreechart是一款使用java进行数据绘图的jar包,功能十分强大,具体有多强大可以参考多年前的博文JFreechart从入门到放弃
  • 经过这么多年,现在我又要用java进行算法设计了,经过多方挑选我还是选择了我最熟悉的jfreechart.
  • 如果你还不知道JFreechart的基本代码以及使用方式这里可以找到常用的demo示例
  • 下面介绍一下使用jfreechart绘制散点图的方法
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.xy.DefaultXYDataset;

import javax.swing.*;
import java.awt.*;

public class test2Dplot {
    double[][] a = {{1, 2, 3}, {4, 5, 6}};

    void plot_2D(double[][] data, String name, String title) {
        DefaultXYDataset xydataset = new DefaultXYDataset();
        xydataset.addSeries(title, data);//设置点的图标title一般表示这画的是决策变量还是目标函数值
        JFreeChart chart = ChartFactory.createScatterPlot(name, "X", "Y", xydataset,
                PlotOrientation.VERTICAL, true, true, false);//设置表头,x轴,y轴,name表示问题的类型

        ChartFrame frame = new ChartFrame("2D scatter plot", chart, true);
        XYPlot xyplot = (XYPlot) chart.getPlot();
        xyplot.setBackgroundPaint(Color.white);//设置背景面板颜色
        ValueAxis vaaxis = xyplot.getDomainAxis();
        vaaxis.setAxisLineStroke(new BasicStroke(1.5f));//设置坐标轴粗细


        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);


    }


    public static void main(String arg[]) {
        test2Dplot test2dplot_ = new test2Dplot();
        test2dplot_.plot_2D(test2dplot_.a, "nils1", "2ddcv");
    }
}

  • 从代码中可以看出,Jfreechart需要有几个要素,
  1. 首先要新建一个Dataset
  2. xydataset.addSeries(title, data); 设置数据和标题,其中数据data是一个2*N的二维数组,N表示数据点的数量。
  3. 通过ChartFactory.createScatterPlot设置一个表格形式
  4. 新建一个frame用于画图
  5. XYPlot xyplot = (XYPlot) chart.getPlot(); 然后通过这个xyplot设置图像的各种属性,比如线条颜色,粗细,坐标轴,等等
  6. 最后是一系列套话-这是从awt和swing中继承的,不多说
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
  • 然后看看效果
posted @ 2021-03-02 21:41  WUST许志伟  阅读(756)  评论(0编辑  收藏  举报