JFreeChart XYLineAndShapeRenderer show unwanted vales outside range start and finish - jfreechart

Im build a series graph with jfreechart using XYLineAndShapeRenderer, this series need to show values for each day of a month, then I need that the X axis shows values from 1 to 30 or 1 to 31 (depend of current month). The dataset only have X values from 1 to 30/31, but the resultant graph shows ZERO(before 1) and 31/32 after(30/31). I want to show only 1 to 30/31 on X axis. But I dont have success. Follow shows the code that build dataset and graph and resultante image.
How I can show only valid values on X axis in this case ?
// build dataset
private XYDataset createSampleData()
{
List<Integer> diario = new ArrayList<>(Arrays.asList(20, 50, 120, 78, 37, 69, 145));
int dSize = diario.size();
int dPos = 0;
XYSeries serieD = new XYSeries("Diário");
XYSeries serieA = new XYSeries("Acumulado");
int acumulado = 0;
for(int i=1; i < 31; i++) {
int valDay = diario.get(dPos++);
acumulado += valDay;
serieD.add(i, valDay);
serieA.add(i, acumulado);
if( dPos >= dSize ) {
dPos = 0;
}
}
XYSeriesCollection result = new XYSeriesCollection(serieD);
result.addSeries(serieA);
return result;
}
private JFreeChart buildSeriesChartBySeriesData(String title, String labelX, String labelY)
{
NumberAxis xAxis = new NumberAxis(labelX);
xAxis.setAutoRangeIncludesZero(false);
xAxis.setRangeType(RangeType.POSITIVE);
NumberAxis yAxis = new NumberAxis(labelY);
yAxis.setAutoRangeIncludesZero(false);
yAxis.setRangeType(RangeType.POSITIVE);
XYSplineRenderer renderer1 = new XYSplineRenderer();
XYPlot plot = new XYPlot(this.createSampleData(), xAxis, yAxis, renderer1);
plot.setDomainGridlinesVisible(true);
plot.setDomainZeroBaselineVisible(false);
plot.setDomainPannable(false);
plot.setBackgroundPaint(new Color(224, 224,235));
plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinePaint(Color.white);
plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
plot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);
plot.setDomainPannable(false);
plot.setRangePannable(false);
plot.setDomainZeroBaselineVisible(false);
plot.setRangeZeroBaselineVisible(false);
renderer1.setSeriesPaint(0, Color.blue);
renderer1.setSeriesPaint(1, Color.yellow);
plot.setAxisOffset(new RectangleInsets(3, 3, 3, 3));
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
XYLineAndShapeRenderer localXYLineAndShapeRenderer = (XYLineAndShapeRenderer) plot.getRenderer();
localXYLineAndShapeRenderer.setBaseShapesVisible(true);
localXYLineAndShapeRenderer.setBaseShapesFilled(true);
localXYLineAndShapeRenderer.setDrawOutlines(true);
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// show item labels:
final XYItemRenderer renderer = plot.getRenderer();
ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER);
renderer.setBasePositiveItemLabelPosition(position);
final StandardXYItemLabelGenerator generator = new StandardXYItemLabelGenerator();
renderer.setSeriesItemLabelGenerator(0, generator);
renderer.setSeriesItemLabelsVisible(0, true);
renderer.setSeriesItemLabelGenerator(1, generator);
renderer.setSeriesItemLabelsVisible(1, true);
JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
return chart;
}
In the next graph, I draw with timeSeries, and the results is the same, showing the last day of previos month and first day of next month, I don not want to show this values.
The result that I need is like this image(a sample from chartJs):
How I can hide the zero and 31 from result of first top graph ?
long time later...
---- after a long time I make the desired graph myself -----
This code generates the right graph:
private JFreeChart TimeSeriesChartExample()
{
XYDataset dataset = createSampleMonthData();
// Create chart
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Time Series Chart Example",
"Date",
"Values",
dataset, true, true, false);
// Changes background color
XYPlot plot = (XYPlot)chart.getPlot();
plot.setBackgroundPaint(new Color(224, 224,235));
XYSplineRenderer renderer1 = new XYSplineRenderer();
renderer1.setSeriesPaint(0, Color.blue);
renderer1.setSeriesPaint(1, Color.green);
plot.setRenderer(renderer1);
plot.setAxisOffset(new RectangleInsets(3, 3, 3, 3));
// show item labels:
XYItemRenderer renderer = plot.getRenderer();
ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER);
renderer.setBasePositiveItemLabelPosition(position);
final StandardXYItemLabelGenerator generator = new StandardXYItemLabelGenerator();
renderer.setSeriesItemLabelGenerator(0, generator);
renderer.setSeriesItemLabelsVisible(0, true);
renderer.setSeriesItemLabelGenerator(1, generator);
renderer.setSeriesItemLabelsVisible(1, true);
DateAxis xAxis = (DateAxis)plot.getDomainAxis();
xAxis.setDateFormatOverride(new SimpleDateFormat("dd/MM/yy"));
ValueAxis domainAxis = plot.getDomainAxis();
domainAxis.setVerticalTickLabels(true);
return chart;
}
This is the resultando graph:

The solution is the follow, I put on the question body too:
private JFreeChart TimeSeriesChartExample()
{
XYDataset dataset = createSampleMonthData();
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Time Series Chart Example",
"Date",
"Values",
dataset, true, true, false);
// Changes background color
XYPlot plot = (XYPlot)chart.getPlot();
plot.setBackgroundPaint(new Color(224, 224,235));
XYSplineRenderer renderer1 = new XYSplineRenderer();
renderer1.setSeriesPaint(0, Color.blue);
renderer1.setSeriesPaint(1, Color.green);
plot.setRenderer(renderer1);
plot.setAxisOffset(new RectangleInsets(3, 3, 3, 3));
XYItemRenderer renderer = plot.getRenderer();
ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER);
renderer.setBasePositiveItemLabelPosition(position);
final StandardXYItemLabelGenerator generator = new StandardXYItemLabelGenerator();
renderer.setSeriesItemLabelGenerator(0, generator);
renderer.setSeriesItemLabelsVisible(0, true);
renderer.setSeriesItemLabelGenerator(1, generator);
renderer.setSeriesItemLabelsVisible(1, true);
DateAxis xAxis = (DateAxis)plot.getDomainAxis();
xAxis.setDateFormatOverride(new SimpleDateFormat("dd/MM/yy"));
ValueAxis domainAxis = plot.getDomainAxis();
domainAxis.setVerticalTickLabels(true);
return chart;
}
This is the result:
Code as tested:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
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.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYSplineRenderer;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.RectangleInsets;
import org.jfree.ui.TextAnchor;
/**
* #see https://stackoverflow.com/a/49909020/230513
*/
public class ChartTest {
private void display() {
JFrame f = new JFrame("ChartTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new ChartPanel(createTimeSeriesChartExample()){
#Override
public Dimension getPreferredSize() {
return new Dimension(1000, 400);
}
});
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private XYDataset createSampleMonthData() {
List<Integer> diario = new ArrayList<>(
Arrays.asList(20, 50, 120, 78, 37, 69, 145));
int dSize = diario.size();
int dPos = 0;
XYSeries serieD = new XYSeries("Diário");
XYSeries serieA = new XYSeries("Acumulado");
int acumulado = 0;
for (int i = 1; i < 31; i++) {
int valDay = diario.get(dPos++);
acumulado += valDay;
serieD.add(i, valDay);
serieA.add(i, acumulado);
if (dPos >= dSize) {
dPos = 0;
}
}
XYSeriesCollection result = new XYSeriesCollection(serieD);
result.addSeries(serieA);
return result;
}
private JFreeChart createTimeSeriesChartExample() {
XYDataset dataset = createSampleMonthData();
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"Time Series Chart Example",
"Date",
"Values",
dataset, true, true, false);
// Changes background color
XYPlot plot = (XYPlot) chart.getPlot();
plot.setBackgroundPaint(new Color(224, 224, 235));
XYSplineRenderer renderer1 = new XYSplineRenderer();
renderer1.setSeriesPaint(0, Color.blue);
renderer1.setSeriesPaint(1, Color.green);
plot.setRenderer(renderer1);
plot.setAxisOffset(new RectangleInsets(3, 3, 3, 3));
XYItemRenderer renderer = plot.getRenderer();
ItemLabelPosition position = new ItemLabelPosition(
ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER);
renderer.setBasePositiveItemLabelPosition(position);
final StandardXYItemLabelGenerator generator =
new StandardXYItemLabelGenerator();
renderer.setSeriesItemLabelGenerator(0, generator);
renderer.setSeriesItemLabelsVisible(0, true);
renderer.setSeriesItemLabelGenerator(1, generator);
renderer.setSeriesItemLabelsVisible(1, true);
DateAxis xAxis = (DateAxis) plot.getDomainAxis();
xAxis.setDateFormatOverride(new SimpleDateFormat("dd/MM/yy"));
ValueAxis domainAxis = plot.getDomainAxis();
domainAxis.setVerticalTickLabels(true);
return chart;
}
public static void main(String[] args) {
EventQueue.invokeLater(new ChartTest()::display);
}
}

Related

Update Jfreechart when update data from Webcam

My jfreeChart comes from frames of a webcam. I pass this frames and it generates a graphic of R, G and B colors of this frame. I want this chart do automatic update as I pass the frames. I've tried everything but nothing seens to work.
Any help is welcome.
class DaemonThread implements Runnable
{
protected volatile boolean runnable = false;
#Override
public void run()
{
synchronized(this)
{
while(runnable)
{
if(webSource.grab())
{
try
{
webSource.retrieve(frame);
Imgcodecs.imencode(".bmp", frame, mem);
Image im = ImageIO.read(new ByteArrayInputStream(mem.toArray()));
buff = (BufferedImage) im;
if(contHistograma==0) {
h = new Histo(buff);
contHistograma++;
}else{
h.update(buff);
}
webcamLabel.setIcon(new ImageIcon(buff));
Graphics g=webcamPanel.getGraphics();
if (g.drawImage(buff, 0, 0, getWidth(), getHeight() -150 , 0, 0, buff.getWidth(), buff.getHeight(), null))
if(runnable == false)
{
System.out.println("Going to wait()");
this.wait();
}
}
catch(Exception ex)
{
System.out.println("Error");
}
}
}
}
}
}
public class Histo{
private ChartFrame lineFrame;
private ArrayList<Integer> redArray;
private ArrayList<Integer> greenArray;
private ArrayList<Integer> blueArray;
public Histo(BufferedImage originalImage){
Color c;
redArray = new ArrayList<>();
greenArray = new ArrayList<>();
blueArray = new ArrayList<>();
for (int i = 0; i < originalImage.getWidth(null); i++) {
for (int j = 0; j < originalImage.getHeight(null); j++) {
c = new Color(originalImage.getRGB(i,j));
redArray.add(c.getRed());
greenArray.add(c.getGreen());
blueArray.add(c.getBlue());
}
}
Collections.sort(redArray);
Collections.sort(greenArray);
Collections.sort(blueArray);
XYSeriesCollection dataset = creatingDataset(redArray, greenArray, blueArray);
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
lineFrame = new ChartFrame("teste", chart);
lineFrame.add(chartPanel);
lineFrame.setVisible(true);
lineFrame.setSize(600, 450);
}
public void update(BufferedImage originalImage){
redArray.clear();
greenArray.clear();
blueArray.clear();
Color c;
for (int i = 0; i < originalImage.getWidth(null); i++) {
for (int j = 0; j < originalImage.getHeight(null); j++) {
c = new Color(originalImage.getRGB(i,j));
redArray.add(c.getRed());
greenArray.add(c.getGreen());
blueArray.add(c.getBlue());
}
}
Collections.sort(redArray);
Collections.sort(greenArray);
Collections.sort(blueArray);
XYSeriesCollection dataset = creatingDataset(redArray, greenArray, blueArray);
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
lineFrame.removeAll();
lineFrame.add(chartPanel);
lineFrame.revalidate();
lineFrame.setLayout(new BorderLayout());
lineFrame.repaint();
}
public static XYSeriesCollection creatingDataset(ArrayList<Integer> redArray,ArrayList<Integer> greenArray,ArrayList<Integer> blueArray){
int cont=1, cont2=1, cont3=1;
XYSeries series = new XYSeries("Red");
XYSeries series2 = new XYSeries("Green");
XYSeries series3 = new XYSeries("Blue");
for (int i = 0; i < redArray.size()-1; i++) {
if(redArray.get(i).intValue() == redArray.get(i+1).intValue()) {
cont++;
}else{
series.add(redArray.get(i).intValue(), cont);
cont=1;
}
}
for (int i = 0; i < greenArray.size()-1; i++) {
if(greenArray.get(i).intValue() == greenArray.get(i + 1).intValue()) {
cont2++;
}else{
series2.add(greenArray.get(i).intValue(), cont2);
cont2 = 1;
}
}
for (int i = 0; i < blueArray.size()-1; i++) {
if(blueArray.get(i).intValue() == blueArray.get(i+1).intValue()) {
cont3++;
}else{
series3.add(blueArray.get(i).intValue(), cont3);
cont3=1;
}
}
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series);
dataset.addSeries(series2);
dataset.addSeries(series3);
return dataset;
}
private JFreeChart createChart(final XYDataset dataset) {
JFreeChart result = ChartFactory.createXYLineChart("Gráfico XY", "Eixo X", "Eixo Y", dataset, PlotOrientation.VERTICAL, true, true, false);
final XYPlot plot = result.getXYPlot();
plot.setBackgroundPaint(new Color(0xffffe0));
plot.setDomainGridlinesVisible(true);
plot.setDomainGridlinePaint(Color.lightGray);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.lightGray);
final NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis(); //RANGE EIXO X
domainAxis.setRange(0, 260);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); //RANGE EIXO Y
rangeAxis.setRange(0, 5000);
return result;
}
}
If someone else have this problem here is the answer:
Chartframe can't get rid of chartpanel, so I made Chartpanel a atribute.
After that I update my dataset and did this:
JFreeChart chart = createChart(dataset);
chartPanel.setChart(chart);
lineFrame.setLayout(new BorderLayout());
lineFrame.repaint();
Problem solved.

How to change the color of multiple ellipses using a loop (JFreeChart)

I have drawn multiple ellipses using a loop as shown below, and the results are perfect using one color for all the ellipses, but my target is to color each ellipse with different color. Is there any way to let the property Color.BLUE change its value in each iteration?
for (int i = 0; i < 3; i++)
{
XYShapeAnnotation unitCircle1 = new XYShapeAnnotation(
new Ellipse2D.Double((FinalArayOfOptpar[s][i] - Math.abs(FinalArayOfOptpar[s][i + 2])),
(FinalArayOfOptpar[s][i + 1] - Math.abs(FinalArayOfOptpar[s][i + 3])),
Math.abs(FinalArayOfOptpar[s][i + 2] * 2.0), Math.abs(FinalArayOfOptpar[s][i + 3] * 2.0)),
new BasicStroke(0.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10.2f), Color.BLUE);
xyPlot.addAnnotation(unitCircle1);
}
tens of XYShapeAnnotations will be created…so creating multiple instances of XYShapeAnnotation will not work for my purpose.
Happily, an instance XYShapeAnnotation is small—just 48 bytes each in the example below. You'll want to profile to be sure.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.geom.Ellipse2D;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.XYShapeAnnotation;
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/35236100/230513
*/
public class AnnotationTest {
private static final BasicStroke stroke = new BasicStroke(2.0f);
private static final int N = 16;
private static final int S = 8;
public static void main(String[] args) {
EventQueue.invokeLater(new AnnotationTest()::display);
}
private void display() {
XYDataset data = createDataset();
JFreeChart chart = ChartFactory.createXYLineChart("ArcTest", "X", "Y",
data, PlotOrientation.VERTICAL, true, true, false);
XYPlot plot = chart.getXYPlot();
XYLineAndShapeRenderer renderer
= (XYLineAndShapeRenderer) plot.getRenderer();
renderer.setBaseShapesVisible(true);
for (int i = 0; i < N; i++) {
double x = data.getXValue(0, i) - S / 2;
double y = data.getYValue(0, i) - S / 2;
Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, S, S);
Color color = Color.getHSBColor((float) i / N, 1, 1);
renderer.addAnnotation(new XYShapeAnnotation(ellipse, stroke, color));
}
ChartFrame frame = new ChartFrame("Test", chart);
frame.pack();
frame.setVisible(true);
}
private static XYDataset createDataset() {
XYSeriesCollection result = new XYSeriesCollection();
XYSeries series = new XYSeries("ArcTest");
for (int i = 0; i < N; i++) {
series.add(i * S, i * S);
}
result.addSeries(series);
return result;
}
}

How to hide an animated image on canvas?

I created an animated image to move on my canvas then I created another animated image ;
I want to hide just my first image after it's movement and before moving another;
I tried to set opacity of my drawing visual or image brush or etc zero;but all of my image
hide;
List<EllipseGeometry> eg = new List<EllipseGeometry>();
Path ballPath;
int c = 0;
foreach (Polyline p in pl)
{
if (p.Points.Count > 1)
{
ballPath = new Path();
FormattedText formattedText = new FormattedText(" " + (anl[c].DOffset).ToString() + "\n " + anl[c].playername + " ", CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface("arial"),
20,
Brushes.Black);
formattedText.MaxTextWidth = 500;
formattedText.MaxTextHeight = 500;
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawImage(il[c].Source, new Rect(4, 0, 26, 26));//30
drawingContext.DrawText(formattedText, new Point(1, 2));
drawingContext.Close();
RenderTargetBitmap bmp = new RenderTargetBitmap((int)formattedText.WidthIncludingTrailingWhitespace, (int)formattedText.Height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
ImageBrush b = new ImageBrush(bmp);
b.Stretch = Stretch.Uniform;
ballPath.Fill = b;
mainwindow.animecan.Children.Add(ballPath);
////
int jy = 0;
for (int i = 0; i < anl.Count; i++)
{
try
{
if (anl[i].offset == m)
jy = anl[i].offset;
}
catch
{
}
}
if (multi && p.Uid == jy.ToString())//اگر آفست مالتی اسپید شده باشه
{
eg.Add(new EllipseGeometry(ms[ih].p1, 27, 27));
ballPath.Data = eg.First();// animatedEllipseGeometry;
PathFigure myPathFigure = new PathFigure();
PointCollection pe = new PointCollection();
pe.Add(ms[ih].p1);
pe.Add(ms[ih].p2);
myPathFigure.StartPoint = eg.First().Center;
myPathFigure.Segments.Add(
new PolyLineSegment(pe, true));
PathGeometry myPathGeometry = new PathGeometry();
myPathGeometry.Figures.Add(myPathFigure);
myPathGeometry = new PathGeometry();
myPathGeometry.Figures.Add(myPathFigure);//
PointAnimationUsingPath centerPointAnimation1 = new PointAnimationUsingPath();
centerPointAnimation1.PathGeometry = myPathGeometry;
centerPointAnimation1.Duration = TimeSpan.FromSeconds(ms[ih].sspeed);
centerPointAnimation1.BeginTime = TimeSpan.FromSeconds(ms[ih].delay);
centerPointAnimation1.FillBehavior = FillBehavior.HoldEnd;
eg.First().BeginAnimation(EllipseGeometry.CenterProperty, centerPointAnimation1);
eg.Remove(eg.First());
}
c++;
I believe that your problem is caused because your whole code block is executed 'at once' (before updating the UI), rather than 'line by line'. In order to make your call to the Visibility property update before execution reaches the end of the code block, you'll need to queue it on the Dispatcher object. Try this:
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate
{
yourControl.Visibility = Visibility.Collapsed;
});

JFreeChart XY plot: change domain scale

I create the following XY chart:
In this instance, I have two axes, each with two series. And each series has 39 points.
I would like to know how to change the scale of the domain axis, so for example instead of 0-39, it would show 0-3.9.
How can this be achieved? My code for the graph is below:
private final static int SERIES_MIN = 0;
private final static int SERIES_MAX = 1;
private JFreeChart createXYLineChart(String title) {
XYDataset voltageDataset = createXYVoltageDataset();
XYDataset currentDataset = createXYCurrentDataset();
XYLineAndShapeRenderer rVoltage = new XYLineAndShapeRenderer();
rVoltage.setSeriesPaint(SERIES_MIN, new Color(0xAA, 0xAA, 0xFF));
rVoltage.setSeriesPaint(SERIES_MAX, new Color(0x00, 0x00, 0xAA));
rVoltage.setSeriesShapesVisible(SERIES_MIN, false);
rVoltage.setSeriesShapesVisible(SERIES_MAX, false);
float dashVoltage[] = {1.0f, 5f}; // on, off
rVoltage.setSeriesStroke(SERIES_MIN, new BasicStroke(2.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 5, dashVoltage, 0));
rVoltage.setSeriesStroke(SERIES_MAX, new BasicStroke(1f));
XYLineAndShapeRenderer rCurrent = new XYLineAndShapeRenderer();
rCurrent.setSeriesPaint(SERIES_MIN, new Color(0x66, 0xAA, 0x66));
rCurrent.setSeriesPaint(SERIES_MAX, new Color(0x00, 0x44, 0x00));
rCurrent.setSeriesShapesVisible(SERIES_MIN, false);
rCurrent.setSeriesShapesVisible(SERIES_MAX, false);
float dashCurrent[] = {1.0f, 5f}; // on, off
rCurrent.setSeriesStroke(SERIES_MIN, new BasicStroke(2.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER, 5, dashCurrent, 0));
rCurrent.setSeriesStroke(SERIES_MAX, new BasicStroke(1));
JFreeChart chart = ChartFactory.createXYLineChart("Profile", "Set Current", "Voltage", null);
XYPlot plot = (XYPlot) chart.getPlot();
plot.setDataset(SERIES_MIN, voltageDataset);
plot.setRenderer(SERIES_MIN, rVoltage);
plot.setDataset(SERIES_MAX, currentDataset);
plot.setRenderer(SERIES_MAX, rCurrent);
plot.setRangeAxis(SERIES_MAX, new NumberAxis("Actual Current"));
plot.mapDatasetToRangeAxis(SERIES_MAX, SERIES_MAX); //2nd dataset to 2nd y-axi
plot.setBackgroundPaint(new Color(0xFF, 0xFF, 0xFF));
plot.setDomainGridlinePaint(new Color(0x00, 0x00, 0xff));
plot.setRangeGridlinePaint(new Color(0xff, 0x00, 0x00));
return chart;
}
private XYDataset createXYVoltageDataset() {
final XYSeries s1 = new XYSeries("Min Voltage");
final XYSeries s2 = new XYSeries("Max Voltage");
for (int i = 0; i < profile.getNumSteps(); i++) s1.add(i, profile.getStepMinVoltage(i));
for (int i = 0; i < profile.getNumSteps(); i++) s2.add(i, profile.getStepMaxVoltage(i));
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(s1);
dataset.addSeries(s2);
return dataset;
}
private XYDataset createXYCurrentDataset() {
final XYSeries s1 = new XYSeries("Min Current");
final XYSeries s2 = new XYSeries("Max Current");
for (int i = 0; i < profile.getNumSteps(); i++){
s1.add(i, profile.getStepMinCurrent(i));
}
for (int i = 0; i < profile.getNumSteps(); i++) s2.add(i, profile.getStepMaxCurrent(i));
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(s1);
dataset.addSeries(s2);
return dataset;
}
You should be able to use setRange() on the domain axis.
NumberAxis domainAxis = new NumberAxis("Set Current");
domainAxis.setRange(0, 3.9);
plot.setDomainAxis(SERIES_MAX, domainAxis);

JFreeChart : How to draw the moving average over a OHLC chart

I am trying to overlay a moving average over an OHLC chart but it does not seem to work.
I provide two critical functions of the code :
private static OHLCDataset createPriceDataset(String filename)
{
OHLCSeries s1 = new OHLCSeries(filename);
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
DateFormat df = new SimpleDateFormat("yyyyMMdd");
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() );
//double adjClose = Double.parseDouble( st.nextToken() );
s1.add(new Day(date), open, high, low, 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);
XYItemRenderer renderer1 = new HighLowRenderer();
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);
XYPlot plot1 = new XYPlot(data1, domainAxis, rangeAxis, renderer1);
plot1.setBackgroundPaint(Color.lightGray);
plot1.setDomainGridlinePaint(Color.white);
plot1.setRangeGridlinePaint(Color.white);
plot1.setRangePannable(true);
//Overlay the Long-Term Trend Indicator
XYDataset dataset3 = MovingAverage.createMovingAverage(data1, "LT", 49.0, 49.0);
plot1.setDataset(1, dataset3);
plot1.setRenderer(1, new StandardXYItemRenderer());
//add a second dataset (volume) and renderer
IntervalXYDataset data2 = createVolumeDataset(filename);
XYBarRenderer renderer2 = new XYBarRenderer();
renderer2.setDrawBarOutline(false);
renderer2.setBaseToolTipGenerator(new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT, new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0,000.00")));
renderer2.setSeriesPaint(0, Color.red);
XYPlot plot2 = new XYPlot(data2, null, new NumberAxis("Volume"), renderer2);
plot2.setBackgroundPaint(Color.lightGray);
plot2.setDomainGridlinePaint(Color.white);
plot2.setRangeGridlinePaint(Color.white);
CombinedDomainXYPlot cplot = new CombinedDomainXYPlot(domainAxis);
cplot.add(plot1, 3);
cplot.add(plot2, 2);
cplot.setGap(8.0);
cplot.setDomainGridlinePaint(Color.white);
cplot.setDomainGridlinesVisible(true);
cplot.setDomainPannable(true);
//return the new combined chart
JFreeChart chart = new JFreeChart("Sun Microsystems (SUNW)", JFreeChart.DEFAULT_TITLE_FONT, cplot, false);
ChartUtilities.applyCurrentTheme(chart);
renderer2.setShadowVisible(false);
renderer2.setBarPainter(new StandardXYBarPainter());
return chart;
}
Any ideas?
Thank you.
I've added the following code and it seems to work.
If anybody disagrees on this solution just let me know.
Here it goes :
public class PriceVolumeChart2 extends ApplicationFrame{
final static String filename = "A.txt";
*static TimeSeries t1 = new TimeSeries("49-day moving average");*
/**
* Default constructor
*/
public PriceVolumeChart2(String title)
{
super(title);
JPanel panel = createDemoPanel();
panel.setPreferredSize(new Dimension(500, 270));
setContentPane(panel);
}
//create price dataset
//hard-coded here
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("yyyyMMdd");
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() );
//double adjClose = 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;
}
//create volume dataset
private static IntervalXYDataset createVolumeDataset(String filename)
{
//create dataset 2...
TimeSeries s1 = new TimeSeries("Volume");
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
DateFormat df = new SimpleDateFormat("yyyyMMdd");
String inputLine;
in.readLine();
while ((inputLine = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(inputLine, ",");
Date date = df.parse( st.nextToken() );
st.nextToken();
st.nextToken();
st.nextToken();
st.nextToken();
double volume = Double.parseDouble( st.nextToken() );
//double adjClose = Double.parseDouble( st.nextToken() );
s1.add(new Day(date), volume);
}
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
return new TimeSeriesCollection(s1);
}
private static JFreeChart createCombinedChart()
{
OHLCDataset data1 = createPriceDataset(filename);
XYItemRenderer renderer1 = new HighLowRenderer();
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);
XYPlot plot1 = new XYPlot(data1, domainAxis, rangeAxis, renderer1);
plot1.setBackgroundPaint(Color.lightGray);
plot1.setDomainGridlinePaint(Color.white);
plot1.setRangeGridlinePaint(Color.white);
plot1.setRangePannable(true);
//Overlay the Long-Term Trend Indicator
*TimeSeries dataset3 = MovingAverage.createMovingAverage(t1, "LT", 49, 49);
TimeSeriesCollection collection = new TimeSeriesCollection();
collection.addSeries(dataset3);
plot1.setDataset(1, collection);*
plot1.setRenderer(1, new StandardXYItemRenderer());
//add a second dataset (volume) and renderer
IntervalXYDataset data2 = createVolumeDataset(filename);
XYBarRenderer renderer2 = new XYBarRenderer();
renderer2.setDrawBarOutline(false);
renderer2.setBaseToolTipGenerator(new StandardXYToolTipGenerator(
StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0,000.00")));
renderer2.setSeriesPaint(0, Color.red);
XYPlot plot2 = new XYPlot(data2, null, new NumberAxis("Volume"), renderer2);
plot2.setBackgroundPaint(Color.lightGray);
plot2.setDomainGridlinePaint(Color.white);
plot2.setRangeGridlinePaint(Color.white);
CombinedDomainXYPlot cplot = new CombinedDomainXYPlot(domainAxis);
cplot.add(plot1, 3);
cplot.add(plot2, 2);
cplot.setGap(8.0);
cplot.setDomainGridlinePaint(Color.white);
cplot.setDomainGridlinesVisible(true);
cplot.setDomainPannable(true);
//return the new combined chart
JFreeChart chart = new JFreeChart("Sun Microsystems (SUNW)",
JFreeChart.DEFAULT_TITLE_FONT, cplot, false);
ChartUtilities.applyCurrentTheme(chart);
renderer2.setShadowVisible(false);
renderer2.setBarPainter(new StandardXYBarPainter());
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: CombinedXYPlotDemo1.java (base)");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
//Download data from web
}
Sample data:
20110103,41.56,42.14,41.41,41.88,3572300
20110104,41.99,42.1,41.18,41.49,3588800
20110105,41.28,41.73,41,41.4,3232700
20110106,41.37,41.84,41.21,41.48,3361400
20110107,41.52,41.8,41.04,41.62,2725900
20110110,41.41,42.72,41.3,42.22,3145800
20110111,42.52,43.31,42.38,42.94,3315400
20110112,43.2,43.41,42.96,43.13,2463100
20110113,42.88,43.23,42.87,42.97,1676400
20110114,42.79,43.37,42.76,43.26,2215600
20110117,43.26,43.26,43.26,43.26,0
20110118,43.33,44.45,43.32,44.35,2982300
20110119,44.16,44.29,42.27,42.43,4537200
20110120,41.95,42.58,41.46,42.29,4874700
20110121,42.5,43.26,42.03,42.11,3004500
20110124,42.18,42.79,42.07,42.77,2067400
20110125,42.77,43.52,42.28,42.69,3132700
20110126,42.82,42.97,42.04,42.57,3927300
20110127,42.77,43.09,42.37,42.45,3189600
20110128,42.5,42.52,40.88,40.98,3629800
20110131,41.21,41.83,40.89,41.83,3690900
20110201,42.07,42.7,41.93,42.05,3388200
20110202,41.75,41.91,40.82,41.23,3970700
20110203,40.93,41.18,40.23,40.99,3522700
20110204,41.19,43.13,40.94,42.99,5197700
20110207,43.45,44.66,43.37,44.44,4569800
20110208,44.65,44.71,43.83,44.17,3734500
20110209,44.01,44.17,43.16,43.43,3779300
20110210,43.22,44.01,42.57,44,3275700
20110211,43.77,45.15,43.65,45.02,4436000
20110214,45,45.42,44.72,44.79,3484400
20110215,44.79,45,42.64,42.65,7328000
20110216,42.91,43.6,42.7,43.57,4159800
20110217,43.38,44,43.02,43.92,2621800
20110218,43.78,44.29,43.65,43.92,4390200
20110221,43.92,43.92,43.92,43.92,0
20110222,43.21,43.75,42.39,42.49,4143600
20110223,42.59,42.75,39.94,40.45,7074200
20110224,40.34,41.55,40.18,41.15,4455700
20110225,41.16,42.41,41.13,42.36,4297500
20110228,42.43,42.65,41.36,42.08,3070200
20110301,41.98,42.49,40.65,40.68,4091300
The new code is inside asterisks.
If you believe that there is a more elegant solution , please let me know.

Resources