scatter plot in jfreechart from database
Asked Answered
Q

1

2

How can i draw scatter plot of datas in mysql database table using jfreechart in java. I have used swing library. Any link would be helpful. I searched google but couldnot find a understanding solution. If you have got code just provide me. Actually i did do barchart and plot it using jfreechart. The code i used for my barchart is here. Here display3 function displays the barchart. How can i modify it to display scatter plot?

public void display3() throws SQLException, ClassNotFoundException{

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    String JDBC_DRIVER="com.mysql.jdbc.Driver";
    String DB_URL="jdbc:mysql://localhost/data2";
    Connection conn;
    Statement stmt;
    String USER = "root";
    String PASS = "";
    try{
        Class.forName(JDBC_DRIVER);
        conn=DriverManager.getConnection(DB_URL,USER,PASS);
        System.out.println("Creating statement...");
        stmt = conn.createStatement();

        String sql;
        sql="SELECT * FROM `production` WHERE crop_id = 1 AND location_id = 1";
        ResultSet rs=stmt.executeQuery(sql);

        while (rs.next()){
            //String student = rs.getString("studentname");
            String yeartext = rs.getString("year_of_production");
            //double value = Double.parseDouble(text);
            String productiontext = rs.getString("production_amount");
            double production = Double.parseDouble(productiontext);
            Integer year = Integer.parseInt(yeartext);

            dataset.setValue(production, "production", year);


        }



        JFreeChart chart = ChartFactory.createBarChart("Bar Graph",// Chart Title
                "Year", //horizontal axis label
                "Paddy Production", // vertical axis label
                dataset, //data
                PlotOrientation.VERTICAL, //orientation of chart
                true, //include legend
                false, // tool tips
                true);//urls
        CategoryPlot p = chart.getCategoryPlot();
        ChartPanel chartPanel = new ChartPanel(chart, false);
        jPanel9.setLayout(new BorderLayout());
        jPanel9.add(chartPanel, BorderLayout.EAST);
        jPanel9.add(chartPanel);
        SwingUtilities.updateComponentTreeUI(this);
        p.setRangeGridlinePaint(blue);

        System.out.println("Database created successfully...");

    } catch(SQLException se) {
        //Handle errors for JDBC
        System.out.println("Connect failed ! ");
        se.printStackTrace();
    }

}       

  I finally solved my problem: 

The refine code is below and it works:

public void display3() throws SQLException, ClassNotFoundException{

        //DefaultCategoryDataset dataset = new DefaultCategoryDataset();
         XYSeriesCollection dataset = new XYSeriesCollection();
         XYSeries series = new XYSeries("production");
        String JDBC_DRIVER="com.mysql.jdbc.Driver";
    String DB_URL="jdbc:mysql://localhost/data2";
    Connection conn;
    Statement stmt;
    String USER = "root";
    String PASS = "";
        try{
            Class.forName(JDBC_DRIVER);
            conn=DriverManager.getConnection(DB_URL,USER,PASS);
            System.out.println("Creating statement...");
            stmt = conn.createStatement();
                        String sql;
                        sql="SELECT * FROM `production` WHERE crop_id = 1 AND location_id = 1";
                        ResultSet rs=stmt.executeQuery(sql);

                        while (rs.next()){
                            //String student = rs.getString("studentname");
                            String yeartext = rs.getString("year_of_production");
                            //double value = Double.parseDouble(text);
                            String productiontext = rs.getString("production_amount");
                            double production = Double.parseDouble(productiontext);
                            double year = Double.parseDouble(yeartext);
                            series.add(year,production) ;
                            //dataset.addSeries(series);




                        }
                        dataset.addSeries(series);

                        JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot","Year","Paddy Production", dataset);

                        //CategoryPlot p = chart.getCategoryPlot();
                         //XYPlot xyplot = (XYPlot)jfreechart.getPlot();
                        //https://mcmap.net/q/671709/-jfreechart-with-scroller
                        ChartPanel chartPanel = new ChartPanel(chart, false);
                        jPanel9.setLayout(new BorderLayout());
                        jPanel9.add(chartPanel, BorderLayout.EAST);
                        jPanel9.add(chartPanel);
                        SwingUtilities.updateComponentTreeUI(this);
                       // p.setRangeGridlinePaint(blue);

                        System.out.println("Database created successfully...");

                }catch(SQLException se){
                    //Handle errors for JDBC
                    System.out.println("Connect failed ! ");
                    se.printStackTrace();
//                    JOptionPane.showMessageDialog(MajorUI.this, err.getMessage());
                    }

    }

The output is: http://i58.tinypic.com/29ynsxh.png

Quaternion answered 6/7, 2014 at 1:20 Comment(2)
You might take advantage of methods a bit more. Make something like createChart(ResultSet rs). Your code is kinda crazy.Towhaired
Theres an example of a scatter plot here java2s.com/Code/Java/Chart/JFreeChartFastScatterPlotDemo.htmTowhaired
G
5

This complete example creates a suitable database table in memory, queries it into a JDBCXYDataset and displays the dataset in a scatter plot. Note how the first column becomes the domain, while successive columns become individual series.

image

import java.awt.EventQueue;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Random;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.jdbc.JDBCXYDataset;

/**
 * @see https://mcmap.net/q/666192/-scatter-plot-in-jfreechart-from-database
 */
public class JDBCTest {

    private static final int N = 30;
    private static final Random r = new Random();

    private void display() {
        JFrame f = new JFrame("JDBCTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JDBCXYDataset jds = createDataset();
        JFreeChart chart = ChartFactory.createScatterPlot("Inventory",
            "Date", "Count", jds, PlotOrientation.VERTICAL, true, true, false);
        XYPlot plot = chart.getXYPlot();
        plot.setDomainAxis(new DateAxis("Date"));
        f.add(new ChartPanel(chart));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        for (int i = 0; i < jds.getItemCount(); i++) {
            System.out.println(new Date(jds.getX(0, i).longValue()));
        }
    }

    private JDBCXYDataset createDataset() {
        try {
            Connection conn = DriverManager.getConnection(
                "jdbc:h2:mem:test", "", "");
            Statement st = conn.createStatement();
            st.execute("create table inventory(when date, n1 integer, n2 integer)");
            PreparedStatement ps = conn.prepareStatement(
                "insert into inventory values (?, ?, ?)");
            Calendar c = Calendar.getInstance();
            for (int i = 0; i < N; i++) {
                ps.setDate(1, new Date(c.getTimeInMillis()));
                ps.setInt(2, N / 3 + r.nextInt(N / 3));
                ps.setInt(3, N / 2 + r.nextInt(N / 3));
                ps.execute();
                c.add(Calendar.MONTH, 1);
            }
            JDBCXYDataset jds = new JDBCXYDataset(conn);
            jds.executeQuery("select when, n1, n2 from inventory");
            return jds;
        } catch (SQLException ex) {
            ex.printStackTrace(System.err);
        }
        return null;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new JDBCTest().display();
            }
        });
    }
}
Gascon answered 6/7, 2014 at 4:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.