I have one a jfree chart which I can generate everytime I run the code.
Now i want to override few more spider graphs on the same chart. please help me how to do that
Above this i need to add one more spider chart using jfree.
Here is my code for doing this chart.
package com.rectrix.exide.pdfbox;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Paint;
import java.awt.PaintContext;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.ColorModel;
import javax.swing.JPanel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardCategoryToolTipGenerator;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.*;
public class DemoChart extends ApplicationFrame {
public DemoChart(String s)
{
super(s);
JPanel jpanel = createDemoPanel();
jpanel.setPreferredSize(new Dimension(500, 270));
setContentPane(jpanel);
}
private static CategoryDataset createDataset()
{
String s1 = "First";
String s2 = "Second";
String s3 = "Third";
String s4 = "Forth";
String s5 = "Fivth";
String s6 = "Sixth";
String s7 = "Seventh";
String s8 = "Eighth";
String s9 = "Ninth";
String s10 = "Tenth";
DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset();
int count = 5;
int value = 0;
//String keyRow="s";
for (int i=1;i<=10;i++){
value = i*4;
Comparable colKey = 0;
String keyRow = "s"+i;
for(int j=1;j<=count;j++){
colKey = j;
defaultcategorydataset.addValue(value, keyRow, colKey);
}
}
return defaultcategorydataset;
}
public static JFreeChart createChart1(CategoryDataset categorydataset,double d) {
SpiderWebPlot plot = new SpiderWebPlot(categorydataset);
Color bckColor1 = Color.decode("#4282CE"); //Light blue
Paint p = new GradientPaint(0, 1, bckColor1, 0, 1, bckColor1);
plot.setSeriesPaint(p);
JFreeChart chart = new JFreeChart("", plot);
return chart;
}
public static JPanel createDemoPanel()
{
JFreeChart jfreechart = createChart1(createDataset(), 10D);
return new ChartPanel(jfreechart);
}
public static void main(String args[])
{
DemoChart spiderwebchartdemo1 = new DemoChart("JFreeChart: SpiderWebChartDemo1.java");
spiderwebchartdemo1.pack();
RefineryUtilities.centerFrameOnScreen(spiderwebchartdemo1);
spiderwebchartdemo1.setVisible(true);
}
}
Please help me as soon as possible i need to send this build by tomorrow
Thank u in advance for helping and taking efforts to see this.
I want to override few more spider graphs on the same chart.
It may help to examine how a spider web plot is used to display multivariate data. The simplified example below compares just two OBSERVATIONS, each having five VARIABLES named A .. E, with random values in the range 1 .. 3. By chance, the values for variable B coincide; the rest differ. You can adjust the value of OBSERVATIONS to see the effect, but the result becomes progressively more muddled as the number of observations grows. You may want to alter series visibility, as suggested here, or consider these alternatives.
import java.awt.EventQueue;
import java.util.Random;
import javax.swing.JPanel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
/** #see https://stackoverflow.com/a/32885067/230513 */
public class SpiderChart extends ApplicationFrame {
private static final int OBSERVATIONS = 2;
private static final int VARIABLES = 5;
private static final Random r = new Random();
public SpiderChart(String s) {
super(s);
add(createDemoPanel());
}
private static CategoryDataset createDataset() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (int i = 1; i <= OBSERVATIONS; i++) {
String rowKey = "Observation " + i;
for (int j = 1; j <= VARIABLES; j++) {
Comparable colKey = Character.valueOf((char)(j+64));
dataset.addValue(r.nextInt(3) + 1, rowKey, colKey);
}
}
return dataset;
}
public static JFreeChart createChart(CategoryDataset dataset) {
SpiderWebPlot plot = new SpiderWebPlot(dataset);
JFreeChart chart = new JFreeChart("Test", plot);
return chart;
}
public static JPanel createDemoPanel() {
JFreeChart jfreechart = createChart(createDataset());
return new ChartPanel(jfreechart);
}
public static void main(String args[]) {
EventQueue.invokeLater(() -> {
SpiderChart demo = new SpiderChart("SpiderWebChart");
demo.pack();
demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
demo.setVisible(true);
});
}
}
Related
Hi Currently I am trying to import the CSV file into the Java to plot the data, basically, I can import successfully but it does not work in my CSV because it has the time format as: HH:mm:ss MM-dd-yy
The data is as follow:
2016-05-15 00:00:00 0
2016-05-15 00:00:00 0
2016-05-15 00:00:00 5.44852
2016-05-15 00:00:01 0
2016-05-15 00:00:01 0
2016-05-15 00:00:01 5.26064
the code is as follow:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.SimpleDateFormat;
import org.jfree.chart.axis.DateAxis;
import org.jfree.data.time.Minute;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
import au.com.bytecode.opencsv.CSVReader;
public class Test extends ApplicationFrame{
/**
*
*/
private static final long serialVersionUID = 1L;
XYSeriesCollection dataset;
JFreeChart chart;
final ChartPanel chartPanel;
final int chartWidth = 560;
final int chartHeight = 367;
CSVReader reader;
String[] readNextLine;
XYSeries series;
public Test(String applicationTitle) throws IOException {
super(applicationTitle);
dataset = createDataset();
chart = createChart(dataset);
chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(chartHeight,
chartWidth));
this.add(chartPanel);
}
public XYSeriesCollection createDataset() throws NumberFormatException,
IOException {
dataset = new XYSeriesCollection();
try {
reader = new CSVReader(new FileReader("/usr/csv_dump.csv"),'\t');
// Read the header and chuck it away
readNextLine = reader.readNext();
// Set up series
final XYSeries seriesX = new XYSeries("X");
final XYSeries seriesY = new XYSeries("Y");
final XYSeries seriesZ = new XYSeries("Z");
while ((readNextLine = reader.readNext()) != null) {
// add values to dataset
double Time = Double.valueOf(readNextLine[0]);
double X = Long.valueOf(readNextLine[1]);
double Y = Long.valueOf(readNextLine[2]);
double Z = Long.valueOf(readNextLine[3]);
seriesX.add(Time, X);
seriesY.add(Time, Y);
seriesZ.add(Time, Z);
}
System.out.println(seriesX.getMaxX() + "; " + seriesX.getMaxY());
dataset.addSeries(seriesX);
dataset.addSeries(seriesY);
dataset.addSeries(seriesZ);
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
return dataset;
}
public JFreeChart createChart(XYDataset dataset)
throws NumberFormatException, IOException {
chart = ChartFactory.createXYLineChart("Acceleration vs Time", // chart
// title
"Time", // domain axis label
"Acceleration", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // the plot orientation
true, // legend
true, // tooltips
false); // urls
return chart;
}
public static void main(String[] args) throws IOException {
System.out.println("In here, to create a Test");
final Test demo = new Test("Test XY Line chart");
System.out.println("Created, pakcking");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}
but I don't know how to put the time format in this code. Thank you for anyone who can help me with it.
In this simpler example,
Use SimpleDateFormat to parse dates of the given format.
Use ChartFactory.createTimeSeriesChart() to create a time series chart; it will use a DateAxis for the domain.
Data:
2016-05-15 00:00:00, 20
2016-05-15 00:01:01, 21
2016-05-15 00:02:02, 42
Code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
public class Test extends ApplicationFrame {
public Test(String applicationTitle) throws IOException {
super(applicationTitle);
this.add(new ChartPanel(createChart(createDataset())));
}
public XYSeriesCollection createDataset() {
final XYSeries series = new XYSeries("X");
try {
BufferedReader in = new BufferedReader(new FileReader("data.txt"));
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String s = null;
while ((s = in.readLine()) != null) {
String[] a = s.split(",");
Date d = f.parse(a[0]);
int v = Integer.valueOf(a[1].trim());
series.add(d.getTime(), v);
}
} catch (IOException | ParseException e) {
e.printStackTrace(System.err);
}
return new XYSeriesCollection(series);
}
public JFreeChart createChart(XYDataset dataset)
throws NumberFormatException, IOException {
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Acceleration vs Time", "Time", "Acceleration", dataset,
true, true, false);
return chart;
}
public static void main(String[] args) throws IOException {
final Test demo = new Test("Test Time Series Chart");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}
My requirement is to create a dynamic time series stacked area chart in a java desktop app. Something like this example, but i want Stacked Area chart. I have found lot of examples of stacked area chart but they all are based on static data.
Here is the modified version of this example for dynamic time series stacked area chart.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.Timer;
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.axis.DateTickUnit;
import org.jfree.chart.axis.DateTickUnitType;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.SeriesRenderingOrder;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.StackedXYAreaRenderer;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimePeriod;
import org.jfree.data.time.TimeTableXYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
public class DTSCTest extends ApplicationFrame {
private static final String TITLE = "Dynamic Series";
private static final String START = "Start";
private static final String STOP = "Stop";
private static final float MINMAX = 100;
private static final int COUNT = 15;
private static final int FAST = 1000;
private static final int SLOW = FAST * 5;
private static final Random random = new Random();
private Timer timer;
private static final String SERIES1 = "Positive";
private static final String SERIES2 = "Negative";
public DTSCTest(final String title) {
super(title);
final TimeTableXYDataset dataset = new TimeTableXYDataset();
JFreeChart chart = createAreaChart(dataset);
final JButton run = new JButton(STOP);
run.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if (STOP.equals(cmd)) {
timer.stop();
run.setText(START);
} else {
timer.start();
run.setText(STOP);
}
}
});
final JComboBox combo = new JComboBox();
combo.addItem("Fast");
combo.addItem("Slow");
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if ("Fast".equals(combo.getSelectedItem())) {
timer.setDelay(FAST);
} else {
timer.setDelay(SLOW);
}
}
});
this.add(new ChartPanel(chart), BorderLayout.CENTER);
JPanel btnPanel = new JPanel(new FlowLayout());
btnPanel.add(run);
btnPanel.add(combo);
this.add(btnPanel, BorderLayout.SOUTH);
timer = new Timer(FAST, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TimePeriod period = new Second();
dataset.add(period, randomValue(), SERIES1);
dataset.add(period, randomValue(), SERIES2);
if(dataset.getItemCount() > COUNT) {
TimePeriod firstItemTime = dataset.getTimePeriod(0);
dataset.remove(firstItemTime, SERIES1);
dataset.remove(firstItemTime, SERIES2);
}
}
});
}
private float randomValue() {
float randValue = (float) (random.nextGaussian() * MINMAX / 3);
return randValue < 0 ? -randValue : randValue;
}
private JFreeChart createAreaChart(final TimeTableXYDataset dataset) {
final JFreeChart chart = ChartFactory.createStackedXYAreaChart(
"Live Sentiment Chart", "Time", "Sentiments", dataset, PlotOrientation.VERTICAL, true, true, false);
final StackedXYAreaRenderer render = new StackedXYAreaRenderer();
render.setSeriesPaint(0, Color.RED);
render.setSeriesPaint(1, Color.GREEN);
DateAxis domainAxis = new DateAxis();
domainAxis.setAutoRange(true);
domainAxis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss"));
domainAxis.setTickUnit(new DateTickUnit(DateTickUnitType.SECOND, 1));
XYPlot plot = (XYPlot) chart.getPlot();
plot.setRenderer(render);
plot.setDomainAxis(domainAxis);
plot.setSeriesRenderingOrder(SeriesRenderingOrder.FORWARD);
plot.setForegroundAlpha(0.5f);
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setNumberFormatOverride(new DecimalFormat("#,###.#"));
rangeAxis.setAutoRange(true);
return chart;
}
public void start() {
timer.start();
}
public static void main(final String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
DTSCTest demo = new DTSCTest(TITLE);
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
demo.start();
}
});
}
}
Hi i want to draw cross hair on this barchar .Can somone help me.I jst want the cross hair to print X and y cordinates where my mouse is pointing or clicking.I m fine even if the cross hair prints X and Y cordinates on console .here's my code
import java.awt.Color;
import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import javax.swing.JPanel;
import org.jfree.chart.ChartColor;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.Marker;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.HighLowRenderer;
import org.jfree.chart.renderer.xy.StandardXYBarPainter;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.ohlc.OHLCSeries;
import org.jfree.data.time.ohlc.OHLCSeriesCollection;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
public class PriceVolumeChart2 extends ApplicationFrame {
final static String filename = "D:\\CL.txt";
/**
* Default constructor
*/
public PriceVolumeChart2(String title) {
super(title);
JPanel panel = createDemoPanel();
panel.setPreferredSize(new Dimension(1200, 800));
setContentPane(panel);
}
private static OHLCDataset createPriceDataset(String filename) {
// the following data is taken from http://finance.yahoo.com/
// for demo purposes...
OHLCSeries s1 = new OHLCSeries(filename);
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String inputLine;
in.readLine();
while ((inputLine = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(inputLine, ",");
Date date = df.parse(st.nextToken());
double open = Double.parseDouble(st.nextToken());
double high = Double.parseDouble(st.nextToken());
double low = Double.parseDouble(st.nextToken());
double close = Double.parseDouble(st.nextToken());
s1.add(new Day(date), open, high, low, close);
//t1.add(new Day(date), close);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
OHLCSeriesCollection dataset = new OHLCSeriesCollection();
dataset.addSeries(s1);
return dataset;
}
private static JFreeChart createCombinedChart() {
OHLCDataset data1 = createPriceDataset(filename);
System.out.println(data1.getItemCount(0));
HighLowRenderer renderer1 = new HighLowRenderer();
renderer1.setTickLength(3);
renderer1.setBaseToolTipGenerator(new StandardXYToolTipGenerator
(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00")));
renderer1.setSeriesPaint(0, Color.blue);
DateAxis domainAxis = new DateAxis("Date");
NumberAxis rangeAxis = new NumberAxis("Price");
rangeAxis.setNumberFormatOverride(new DecimalFormat("$0.00"));
rangeAxis.setAutoRange(true);
rangeAxis.setAutoRangeIncludesZero(false);
ChartColor chartColor=new ChartColor(0, 0, 0);
XYPlot plot1 = new XYPlot(data1, domainAxis, rangeAxis, renderer1);
plot1.getRangeCrosshairPaint();
plot1.setRangePannable(true);
JFreeChart chart = new JFreeChart("NSE NIFTY", JFreeChart.DEFAULT_TITLE_FONT, plot1, false);
//ChartUtilities.applyCurrentTheme(chart);
return chart;
}
// create a panel
public static JPanel createDemoPanel() {
JFreeChart chart = createCombinedChart();
return new ChartPanel(chart);
}
public static void main(String[] args) {
// TODO code application logic here
PriceVolumeChart2 demo = new PriceVolumeChart2("JFreeChart");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
// Download data from web
}
this is my output.N i want crosshair to tell me the x and y coordinates according to given values in X and Y axis
You can enable the trace feature to follow the mouse, as shown here. You can add a ChartMouseListener to see the ChartEntity under the mouse, as shown here.
Addendum: Given a these instatiations,
JFreeChart chart = new JFreeChart(…);
chartPanel = new ChartPanel(chart);
This complete example enables trace:
chartPanel.setHorizontalAxisTrace(true);
chartPanel.setVerticalAxisTrace(true);
This complete example adds a ChartMouseListener:
chartPanel.addChartMouseListener(new ChartMouseListener() {
#Override
public void chartMouseClicked(ChartMouseEvent e) {
final ChartEntity entity = e.getEntity();
System.out.println(entity + " " + entity.getArea());
}
#Override
public void chartMouseMoved(ChartMouseEvent e) {
}
});
Hey guys i found the answer to this ..Thanks trashgod for helping me out..The following code helps to draw a barchart with a moving cross hair and the y coordinate is displayed on a JLabel.The CL.txt file contains nothing but date,open,close,high,low (all are double values).
import java.awt.Color;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import javax.swing.JLabel;
import org.jfree.chart.ChartColor;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.HighLowRenderer;
import org.jfree.data.time.Day;
import org.jfree.data.time.ohlc.OHLCSeries;
import org.jfree.data.time.ohlc.OHLCSeriesCollection;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RefineryUtilities;
/**
* An example showing how to convert the mouse location to chart coordinates.
*/
public class MouseListenerDemo4 extends ApplicationFrame
implements ChartMouseListener {
private JFreeChart chart;
private ChartPanel chartPanel;
private JLabel priceLabel;
public MouseListenerDemo4(String title) {
super(title);
priceLabel=new JLabel("");
priceLabel.setBounds(5000, 5, 50, 20);
String chartTitle = "Mouse Listener Demo 4";
String file="D:\\CL.txt";
OHLCDataset data2 = createPriceDataset(file);
System.out.println(data2.getItemCount(0));
HighLowRenderer renderer1 = new HighLowRenderer();
renderer1.setTickLength(3);
renderer1.setBaseToolTipGenerator(new StandardXYToolTipGenerator
(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00")));
renderer1.setSeriesPaint(0, Color.blue);
DateAxis domainAxis = new DateAxis("Date");
NumberAxis rangeAxis = new NumberAxis("Price");
rangeAxis.setNumberFormatOverride(new DecimalFormat("$0.00"));
rangeAxis.setAutoRange(true);
rangeAxis.setAutoRangeIncludesZero(false);
ChartColor chartColor=new ChartColor(0, 0, 0);
XYPlot plot1 = new XYPlot(data2, domainAxis, rangeAxis, renderer1);
plot1.getRangeCrosshairPaint();
plot1.setBackgroundPaint(Color.white);
plot1.setDomainGridlinePaint(Color.magenta);
plot1.setRangeGridlinePaint(Color.magenta);
plot1.setRangePannable(true);
plot1.setRangeCrosshairVisible(true);
plot1.setRangeCrosshairValue(4000, true);
plot1.setRangeCrosshairLockedOnData(true);
plot1.setRangeCrosshairVisible(true);
this.chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot1, false);
chartPanel = new ChartPanel(this.chart);
chartPanel.setPreferredSize(new java.awt.Dimension(1000, 500));
chartPanel.setMouseZoomable(true, false);
chartPanel.addChartMouseListener(this);
setContentPane(chartPanel);
priceLabel.setBackground(Color.cyan);
chartPanel.add(priceLabel);
priceLabel.setVisible(true);
priceLabel.setText("");
}
private static OHLCDataset createPriceDataset(String filename) {
// the following data is taken from http://finance.yahoo.com/
// for demo purposes...
OHLCSeries s1 = new OHLCSeries(filename);
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String inputLine;
in.readLine();
while ((inputLine = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(inputLine, ",");
Date date = df.parse(st.nextToken());
double open = Double.parseDouble(st.nextToken());
double high = Double.parseDouble(st.nextToken());
double low = Double.parseDouble(st.nextToken());
double close = Double.parseDouble(st.nextToken());
double volume = Double.parseDouble(st.nextToken());
s1.add(new Day(date), open, high, low, close);
//t1.add(new Day(date), close);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
OHLCSeriesCollection dataset = new OHLCSeriesCollection();
dataset.addSeries(s1);
return dataset;
}
/**
* Creates a sample dataset.
*
* #return The dataset.
*/
/**
* Receives chart mouse click events.
*
* #param event the event.
*/
public void chartMouseClicked(ChartMouseEvent event) {
int mouseX = event.getTrigger().getX();
int mouseY = event.getTrigger().getY();
System.out.println("x = " + mouseX + ", y = " + mouseY);
Point2D p = chartPanel.translateScreenToJava2D(
new Point(mouseX, mouseY));
XYPlot plot = (XYPlot) chart.getPlot();
Rectangle2D plotArea = this.chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();
ValueAxis domainAxis = plot.getDomainAxis();
RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
ValueAxis rangeAxis = plot.getRangeAxis();
RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();
double chartX = domainAxis.java2DToValue(p.getX(), plotArea,
domainAxisEdge);
double chartY = rangeAxis.java2DToValue(p.getY(), plotArea,
rangeAxisEdge);
this.chartPanel.setHorizontalAxisTrace(true);
this.chartPanel.setVerticalAxisTrace(true);
System.out.println("Chart: x = " + chartX + ", y = " + (int)chartY);
priceLabel.setText(""+(int)chartY);
}
/**
* Receives chart mouse moved events.
*
* #param event the event.
*/
public void chartMouseMoved(ChartMouseEvent event) {
// ignore
}
/**
* Starting point for the demonstration application.
*
* #param args ignored.
*/
public static void main(String[] args) {
MouseListenerDemo4 demo = new MouseListenerDemo4(
"Mouse Listener Demo 4");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}
I'm making a GUI that display result of background calculations. But before that, I wanted to test changing the dataset. Here is my code:
DefaultXYDataset dataset = new DefaultXYDataset();
#Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < periods; i++) {
series[0][i] = (double) i;
series[1][i] = 0;
}
dataset.addSeries("Series0", series);
for (int it = 0; it < 10; it++) {
series[1][random.nextInt(periods)] = random.nextInt(100) / 2;
double[][] d = new double[2][periods];
for (int i = 0; i < periods; i++) {
d[0][i] = series[0][i];
d[1][i] = series[1][i];
}
dataset.removeSeries("Series0");
dataset.addSeries("Series0", series);
// try {
// Thread.sleep(100);
// } catch (java.lang.InterruptedException ex) {
// }
}
As you can see, I want to change points on the graph (every time it finishes 'some complicated computations') - this change is in the thread invoked by me in another class. My problem is that this whole concept is not working. It throws 'Series index out of bounds'-IllegalArgumentException, 'index out of bounds' - of some library inner arraylist etc.. I'm not using DynamicTimeSeriesCollection because I need the X axis to be the number of my inner iterations not the time period, and also update when 'some computations' are finished not every some time period. Can you tell me what I'm doing wrong? Or is there a better way to update/refresh the graph?
Your snippet is incorrectly synchronized; you should update your dataset from the process() method of a SwingWorker, as shown here. Because your domain is "the number of my inner iterations", don't use a DateAxis; instead, use a NumberAxis, as shown in ChartFactory.createXYLineChart().
Addendum: This variation on the example plots the worker's progress on a line chart. Note that createXYLineChart() uses NumberAxis for both domain and range. Given a series in the line chart's dataset, note also how the implementation of process() can safely update the dataset as new data arrives; the listening chart will update itself in response.
private XYSeries series = new XYSeries("Result");
…
#Override
protected void process(List<Double> chunks) {
for (double d : chunks) {
label.setText(df.format(d));
series.add(++n, d);
}
}
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.text.DecimalFormat;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
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.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
/**
* #see https://stackoverflow.com/a/13205322/230513
* #see https://stackoverflow.com/questions/4637215
*/
public final class ChartWorker {
private static final String S = "0.000000000000000";
private final JProgressBar progressBar = new JProgressBar();
private final JLabel label = new JLabel(S, JLabel.CENTER);
private final XYSeries series = new XYSeries("Result");
private final XYDataset dataset = new XYSeriesCollection(series);
private void create() {
JFrame f = new JFrame("√2");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(progressBar, BorderLayout.NORTH);
JFreeChart chart = ChartFactory.createXYLineChart(
"Newton's Method", "X", "Y", dataset,
PlotOrientation.VERTICAL, false, true, false);
XYPlot plot = (XYPlot) chart.getPlot();
plot.getRangeAxis().setRange(1.4, 1.51);
plot.getDomainAxis().setStandardTickUnits(
NumberAxis.createIntegerTickUnits());
XYLineAndShapeRenderer renderer
= (XYLineAndShapeRenderer) plot.getRenderer();
renderer.setSeriesShapesVisible(0, true);
f.add(new ChartPanel(chart) {
#Override
public Dimension getPreferredSize() {
return new Dimension(640, 480);
}
}, BorderLayout.CENTER);
f.add(label, BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
runCalc();
}
private void runCalc() {
progressBar.setIndeterminate(true);
TwoWorker task = new TwoWorker();
task.addPropertyChangeListener((PropertyChangeEvent e) -> {
if ("progress".equals(e.getPropertyName())) {
progressBar.setIndeterminate(false);
progressBar.setValue((Integer) e.getNewValue());
}
});
task.execute();
}
private class TwoWorker extends SwingWorker<Double, Double> {
private static final int N = 5;
private final DecimalFormat df = new DecimalFormat(S);
double x = 1;
private int n;
#Override
protected Double doInBackground() throws Exception {
for (int i = 1; i <= N; i++) {
x = x - (((x * x - 2) / (2 * x)));
setProgress(i * (100 / N));
publish(x);
Thread.sleep(1000); // simulate latency
}
return x;
}
#Override
protected void process(List<Double> chunks) {
for (double d : chunks) {
label.setText(df.format(d));
series.add(++n, d);
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new ChartWorker()::create);
}
}
I am facing problems in adding points to XYSeries. I have two classes. One is Sample (it has a main method) and the other class is JfreeChart (it has JfreeChart Code). In my Sample class I have a 2D array sample[row][2] which has initially 10 rows, and then I need to call the JfreeChart class and add them to XYSeries and display a scatter plot. I managed to do this, but the next time I call the Jfreechart class my Array has 25 rows.
I need to add the values to XYSeries and plot them on a scatter plot which should display the earlier 10 rows' values with different colors and now 25 rows values with different colors… and this goes on. Can anyone give some suggestions or examples?
class Sample {
public static void main(String args[]) {
System.out.print("(X,Y) Paired Values");
double[][] sample = new double[row][2];
for (int g = 0; g < sampe.length; g++) {
for (int h = 0; h < 2; h++) {
System.out.print("" + sample[g][h] + ",");
}
}
JfreeChart sample = new JfreeChart("Demo", sample);
}
static XYDataset samplexydataset2(double[][] sample) {
XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
XYSeries series = new XYSeries("DataSet");
for (int x = 0; x < sample.length; x++) {
series.add(sample[x][0], sample[x][1]);
}
xySeriesCollection.addSeries(series);
return xySeriesCollection;
}
}
1)When I call "First Time" JfreeChart Class I will be having these Pairs in my Sample Array
(0.78,0.80)
(0.21,0.19)
(0.181,0.187)
2)When I call JfreeChart Class "Second time" I will having Diffrent values in my Sample Array
(0.20,0.19)
(0.8,0.79)
(0.41,0.45)
(0.77,0.79)
(0.54,0.65)
And this goes for few times(10 times)So I need add this to "XYSeries" and "XYSeriesCollection" and display the "First time" Values and "Second time" Values when I call Second time JFreeChart Class
You can add new values to the XYSeries using one of the available add() methods, as shown in this example. If you're getting adventitious rows, you'll need to post an sscce.
Addendum: Looking more closely at the (recently updated) genesis of your example, some confusion is understandable: no array is needed at all. The example below includes a button that adds new samples to a second series.
Can I change the Color of Points when I click the "Add" Button?
Each new series is a new color, as shown in this example. To change individual colors, the recommended way is to override the renderer's getItemPaint() method, as shown here.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.util.*;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jfree.chart.*;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
/**
* #see https://stackoverflow.com/questions/7205742
* #see https://stackoverflow.com/questions/7208657
* #see https://stackoverflow.com/questions/7071057
*/
public class ScatterAdd extends JFrame {
private static final int N = 8;
private static final String title = "Scatter Add Demo";
private static final Random rand = new Random();
private XYSeries added = new XYSeries("Added");
public ScatterAdd(String s) {
super(s);
final ChartPanel chartPanel = createDemoPanel();
this.add(chartPanel, BorderLayout.CENTER);
JPanel control = new JPanel();
control.add(new JButton(new AbstractAction("Add") {
#Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < N; i++) {
added.add(rand.nextGaussian(), rand.nextGaussian());
}
}
}));
this.add(control, BorderLayout.SOUTH);
}
private ChartPanel createDemoPanel() {
JFreeChart jfreechart = ChartFactory.createScatterPlot(
title, "X", "Y", createSampleData(),
PlotOrientation.VERTICAL, true, true, false);
XYPlot xyPlot = (XYPlot) jfreechart.getPlot();
xyPlot.setDomainCrosshairVisible(true);
xyPlot.setRangeCrosshairVisible(true);
XYItemRenderer renderer = xyPlot.getRenderer();
renderer.setSeriesPaint(0, Color.blue);
NumberAxis domain = (NumberAxis) xyPlot.getDomainAxis();
domain.setVerticalTickLabels(true);
return new ChartPanel(jfreechart);
}
private XYDataset createSampleData() {
XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
XYSeries series = new XYSeries("Random");
for (int i = 0; i < N * N; i++) {
double x = rand.nextGaussian();
double y = rand.nextGaussian();
series.add(x, y);
}
xySeriesCollection.addSeries(series);
xySeriesCollection.addSeries(added);
return xySeriesCollection;
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ScatterAdd demo = new ScatterAdd(title);
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
demo.pack();
demo.setLocationRelativeTo(null);
demo.setVisible(true);
}
});
}
}