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);
}
}
Related
I would like to add y and x axis lines to my graph. I have tried by setting domain cross hairs by true, but it doesn't appear. Please could i have some help? when I run the program the graph comes up the x and y lines don't appear at x = 0 and y = 0:
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
package Grava;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import org.jfree.chart.axis.NumberAxis;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.fx.ChartViewer;
import org.jfree.chart.panel.CrosshairOverlay;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.Crosshair;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.statistics.Regression;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import java.awt.*;
public class ScatterAdd extends Application {
private final XYSeries series = new XYSeries("Voltage");
private final XYSeries trend = new XYSeries("Trend");
private final XYSeriesCollection dataset = new XYSeriesCollection(series);
ChoiceBox<String> domainLabels = new ChoiceBox<>();
ChoiceBox<String> rangeLabels = new ChoiceBox<>();
private JFreeChart createChart() {
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series);
return ChartFactory.createScatterPlot("VI Characteristics", "Current", "Voltage", dataset);
}
#Override
public void start(Stage stage) {
Image image = new Image("Grava.logo.png");
stage.getIcons().add(image);
XYPlot plot = createChart().getXYPlot();
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) plot.getRenderer();
r.setSeriesLinesVisible(1, Boolean.TRUE);
r.setSeriesShapesVisible(1, Boolean.FALSE);
var equation = new TextField();
series.addChangeListener((event) -> {
double[] coefficients = Regression.getOLSRegression(dataset, 0);
double b = coefficients[0]; // intercept
double m = coefficients[1]; // slope
equation.setText("y = " + m + " x + " + b);
});
JFreeChart chart = createChart();
domainLabels.getSelectionModel().selectedItemProperty().addListener((ov, s0, s1) -> {
chart.getXYPlot().getDomainAxis().setLabel(s1);
});
rangeLabels.getSelectionModel().selectedItemProperty().addListener((ov, s0, s1) -> {
chart.getXYPlot().getRangeAxis().setLabel(s1);
});
domainLabels.getItems().addAll("Current", "Seconds");
domainLabels.setValue("Current");
rangeLabels.getItems().addAll("Voltage", "Metres");
rangeLabels.setValue("Voltage");
var xSpin = new Spinner<Double>(-10000000.000, 10000000.000, 0, 0.1);
xSpin.setEditable(true);
xSpin.setPromptText("Xvalue");
var ySpin = new Spinner<Double>(-10000000.000, 10000000.000, 0, 0.1);
ySpin.setEditable(true);
ySpin.setPromptText("Yvalue");
var button = new Button("Add");
button.setOnAction(ae -> series.add(xSpin.getValue(), ySpin.getValue()));
HBox xBox = new HBox();
xBox.getChildren().addAll(domainLabels);
HBox yBox = new HBox();
yBox.getChildren().addAll(rangeLabels);
var enter = new ToolBar(xBox, xSpin, yBox, ySpin, button, equation);
BorderPane.setAlignment(enter, Pos.CENTER);
BorderPane root = new BorderPane();
root.setCenter(new ChartViewer(chart));
root.setBottom(enter);
stage.setTitle("ScatterAdd");
stage.setScene(new Scene(root, 720, 480));
stage.show();
}
/*
private void adjustAxis(NumberAxis axis, boolean vertical) {
axis.setRange(-3.0, 3.0);
axis.setTickUnit(new NumberTickUnit(0.5));
axis.setVerticalTickLabels(vertical);
}
*/
public static void main(String[] args) {
launch(args);
}
}
The crosshairs do not appear because you invoke createChart() twice, updating one instance while displaying the other. Instead, create and update a single instance:
public void start(Stage stage) {
//XYPlot plot = createChart().getXYPlot();
var chart = createChart();
XYPlot plot = chart.getXYPlot();
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
…
//JFreeChart chart = createChart();
…
}
Incidentally, adding the SeriesChangeListener before creating the chart, as you did here, risks causing Regression to
throw new IllegalArgumentException("Not enough data.");
Consider limiting the effect to two or more items:
series.addChangeListener((event) -> {
if (series.getItemCount() > 1) {
…
}
});
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);
}
}
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);
});
}
}
Requirement: i need to display toolTip(No data available) and image on time series chart which have null data ie; Image 2 on gray color area.
Problem:I am not able to get it.
Image With some data ie; series1.addOrUpdate(absoluteMSecond, data[i]);
Image with null data ie; series1.addOrUpdate(absoluteMSecond, null);
COde:
import java.util.Calendar;
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.ValueAxis;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
public class TextOnJFreeChart extends ApplicationFrame {
public TextOnJFreeChart(final String title) {
super(title);
final XYDataset data = createDataset();
final JFreeChart chart = createChart(data);
final ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
setContentPane(chartPanel);
}
private JFreeChart createChart(final XYDataset data) {
final JFreeChart chart = ChartFactory.createTimeSeriesChart("Text/ToolTip Trying Demo", "X", "Y", data, true, true, true);
final XYPlot plot = chart.getXYPlot();
plot.getRenderer().setToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());
plot.setNoDataMessage("Hai it is ok if i get this message.......");
final DateAxis domainAxis = new DateAxis("Time");
domainAxis.setUpperMargin(0.50);
plot.setDomainAxis(domainAxis);
final ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setUpperMargin(0.30);
rangeAxis.setLowerMargin(0.50);
return chart;
}
private XYDataset createDataset() {
final TimeSeriesCollection result = new TimeSeriesCollection();
result.addSeries(createSupplier1Bids());
return result;
}
private TimeSeries createSupplier1Bids()
{
double[] data = {200.0, 195.0, 190.0, 188.0, 185.0, 180.0};
long timeStamp = System.currentTimeMillis();
Millisecond absoluteMSecond = getTimeInMillisecondFormat(timeStamp, 0L);
final TimeSeries series1 = new TimeSeries("Supplier 1", Millisecond.class);
for(int i = 0; i < data.length; i++)
{
absoluteMSecond = getTimeInMillisecondFormat(timeStamp + i * 1000, 0L);
//series1.addOrUpdate(absoluteMSecond, data[i]);
series1.addOrUpdate(absoluteMSecond, null);
}
return series1;
}
public Millisecond getTimeInMillisecondFormat(long timeStamp, long startTime)
{
try
{
long diff = timeStamp - startTime;
Calendar calender = Calendar.getInstance();
calender.setTimeInMillis(diff);
Millisecond elapsedMSecond = new Millisecond(calender.getTime());
return (elapsedMSecond);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
public static void main(final String[] args) {
final TextOnJFreeChart demo = new TextOnJFreeChart("Text/ToolTip Trying Demo");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}
Thanks in advance
You can specify the desired image to the plot's setBackgroundImage() method, mentioned here and here.
The implementation of getToolTipText() in ChartPanel will return null if the dataset is empty, but you can override the method to return a suitable alternative string.
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();
}
});
}
}