Question

I am trying to create an application which monitors the price of petrol over time. Currently my application has a GUI which displays information as text-- so as a list. However, I now want to add a display which will show the prices graphically. The user can choose to show more than one type of petrol and the graphs are updated automatically every 5 seconds.

I am confused as to how to go about drawing a very simple scatterplot in java. Can anyone make suggestions

Was it helpful?

Solution

Try something like

import javax.swing.*;
import java.awt.geom.*;
import java.awt.Graphics;
import java.util.*;

public class Scatterplot extends JFrame {

    private List points = new ArrayList();

    public Scatterplot() {
        super("Scatterplot");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        points.add(new Point2D.Float(2, 4));
        points.add(new Point2D.Float(16, 15));
        points.add(new Point2D.Float(20, 14));
        points.add(new Point2D.Float(62, 24));
        points.add(new Point2D.Float(39, 84));

        JPanel panel = new JPanel() { 
            public void paintComponent(Graphics g) {
                for(Iterator i=points.iterator(); i.hasNext(); ) {
                    Point2D.Float pt = (Point2D.Float)i.next();
                    g.drawString("X", (int)pt.x, (int)pt.y);
                }
            }
        };

        setContentPane(panel);
        setBounds(20, 20, 200, 200);
        setVisible(true);       
    }
    public static void main(String[] args) {
        new Scatterplot();
    }
}

OTHER TIPS

Use JavaFX. This is a simple line graph example:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.stage.Stage;


public class LineChartSample extends Application {

    @Override public void start(Stage stage) {
        stage.setTitle("Line Chart Sample");
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis();
        xAxis.setLabel("Month");       

        final LineChart<String,Number> lineChart = 
                new LineChart<String,Number>(xAxis,yAxis);

        lineChart.setTitle("Stock Monitoring, 2010");

        XYChart.Series series = new XYChart.Series();
        series.setName("My portfolio");

        series.getData().add(new XYChart.Data("Jan", 23));
        series.getData().add(new XYChart.Data("Feb", 14));
        series.getData().add(new XYChart.Data("Mar", 15));
        series.getData().add(new XYChart.Data("Apr", 24));
        series.getData().add(new XYChart.Data("May", 34));
        series.getData().add(new XYChart.Data("Jun", 36));
        series.getData().add(new XYChart.Data("Jul", 22));
        series.getData().add(new XYChart.Data("Aug", 45));
        series.getData().add(new XYChart.Data("Sep", 43));
        series.getData().add(new XYChart.Data("Oct", 17));
        series.getData().add(new XYChart.Data("Nov", 29));
        series.getData().add(new XYChart.Data("Dec", 25));


        Scene scene  = new Scene(lineChart,800,600);
        lineChart.getData().add(series);

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

You can add a method to update the stage after the use enters the new data.

However, a better approach is to use the animation feature in JavaFX with the charts. Straight form the API:

JavaFX charts lends itself very well for real time or dynamic Charting (like online stocks, web traffic etc) from live data sets. Here is an example of a dynamic chart created with simulated data. A Timeline is used to simulate dynamic data for stock price variations over time(hours).

There is a really good example in the API:

private XYChart.Series<Number,Number> hourDataSeries; 
private NumberAxis xAxis;
private Timeline animation;
private double hours = 0; 
private double timeInHours = 0;
private double prevY = 10;
private double y = 10; 

// timeline to add new data every 60th of a second
animation = new Timeline();
animation.getKeyFrames().add(new KeyFrame(Duration.millis(1000 / 60), new    EventHandler<ActionEvent>() {
    @Override public void handle(ActionEvent actionEvent) {
        // 6 minutes data per frame

      for(int count=0; count < 6; count++) {

        nextTime();
        plotTime();

      }
    }

}));
animation.setCycleCount(Animation.INDEFINITE);

xAxis = new NumberAxis(0,24,3);

  final NumberAxis yAxis = new NumberAxis(0,100,10);
  final LineChart<Number,Number> lc = new LineChart<Number,Number>(xAxis,yAxis);

  lc.setCreateSymbols(false);
  lc.setAnimated(false);
  lc.setLegendVisible(false);
  lc.setTitle("ACME Company Stock");

  xAxis.setLabel("Time");
  xAxis.setForceZeroInRange(false);
  yAxis.setLabel("Share Price");
  yAxis.setTickLabelFormatter(new NumberAxis.DefaultFormatter(yAxis,"$",null));

  hourDataSeries = new XYChart.Series<Number,Number>();
  hourDataSeries.setName("Hourly Data");
  hourDataSeries.getData().add(new XYChart.Data<Number,Number>(timeInHours,prevY));
  lc.getData().add(hourDataSeries);

  private void nextTime() {
      if (minutes == 59) {
          hours ++;
          minutes = 0;
      } else {
          minutes ++;
      }
      timeInHours = hours + ((1d/60d)*minutes);
  }

  private void plotTime() {
      if ((timeInHours % 1) == 0) {
          // change of hour
          double oldY = y;
          y = prevY - 10 + (Math.random()*20);
          prevY = oldY;
          while (y < 10 || y > 90) y = y - 10 + (Math.random()*20);
          hourDataSeries.getData().add(new XYChart.Data<Number, Number>(timeInHours, prevY));
          // after 25hours delete old data
          if (timeInHours > 25) hourDataSeries.getData().remove(0);
          // every hour after 24 move range 1 hour
          if (timeInHours > 24) {
              xAxis.setLowerBound(xAxis.getLowerBound()+1);
              xAxis.setUpperBound(xAxis.getUpperBound()+1);
          }
      }
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top