JFreeChart : How to make a series invisible? - jfreechart

I am trying to make a chart of ohlc bars invisible so that I can leave the window with only the moving average.
Here is the code with the two series (ohlc bars and moving average) :
private static JFreeChart createChart(OHLCDataset dataset)
{
JFreeChart chart = ChartFactory.createHighLowChart(
"HighLowChartDemo2",
"Time",
"Value",
dataset,
true);
XYPlot plot = (XYPlot)chart.getPlot();
DateAxis axis = (DateAxis)plot.getDomainAxis();
axis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
NumberAxis yAxis = (NumberAxis)plot.getRangeAxis();
yAxis.setNumberFormatOverride(new DecimalFormat("$0.00"));
//overlay the moving average dataset...
XYDataset dataset2 = MovingAverage.createMovingAverage(dataset, "-MAVG", 3 * 24 * 60 * 60 * 1000L, 0L);
plot.setDataset(1, dataset2);
plot.setRenderer(1, new StandardXYItemRenderer());
XYItemRenderer theRenderer = plot.getRenderer(0);
theRenderer.setSeriesVisible(0, false);
return chart;
}
For some reason setSeriesVisible function is not working.
Any ideas?
Thank you.

HighLowRenderer ignores getSeriesVisible() and getBaseSeriesVisible(), although it does check getDrawOpenTicks() and getDrawCloseTicks(). You can replace the OHLCDataset:
plot.setDataset(0, null);
Alternatively, don't add the OHLCDataset in the first place; just use it to create the MovingAverage.

Related

How to add shapes to line graph in jfreechart

Edited to add working image at end.
I need to add some sort of annotation to a line graph that I've generated. The red line is the data I'm graphing successfully using a XYLineChart and a XYLineAndShapeRenderer. The squares and text are samples of what I would like to add but have been unable to get working. The data for the graph may be updated as fast as once per second.
Here is how I'm creating the chart:
private JFreeChart createChart(XYDataset dataset) {
final JFreeChart result = ChartFactory.createXYLineChart(
TITLE, // chart title
XAXIS, // domain axis label (x-axis)
YAXIS, // range axis label (y-axis)
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips?
false // URLs?
);
customizeChart(result);
return result;
}
private void customizeChart(final JFreeChart result) {
// NOW DO SOME OPTIONAL CUSTOMIZATION OF THE CHART...
// set the background color for the chart...
result.setBackgroundPaint(null); //makes background transparent.
// get a reference to the plot for further customisation...
XYPlot plot = (XYPlot) result.getPlot();
plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
plot.setRangePannable(false);
XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, true);
// I've also tried to use a spline renderer
// XYSplineRenderer renderer = new XYSplineRenderer();
renderer.setSeriesShapesVisible(0, false);
renderer.setBaseShapesVisible(true);
plot.setRenderer(renderer);
// set the range axis to display integers only...
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
rangeAxis.setTickUnit(new NumberTickUnit(10.0)); //otherwise tick units will randomly change to be 5's sometimes.
//set the max/min values
rangeAxis.setUpperBound(MAX);
rangeAxis.setLowerBound(MIN);
// rangeAxis.setInverted(true);
rangeAxis.setInverted(false);
//get the other axis for work in the next step.
NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
domainAxis.setAutoRange(true);
domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
//do some font stuff
Font axisFont = new Font("Tahoma", Font.BOLD, 12);
Font tickFont = new Font("Tahoma", Font.PLAIN, 11);
Font titleFont = new Font("Tahoma", Font.BOLD, 18);
result.getTitle().setFont(titleFont);
rangeAxis.setLabelFont(axisFont);
rangeAxis.setTickLabelFont(tickFont);
domainAxis.setLabelFont(axisFont);
domainAxis.setTickLabelFont(tickFont);
}
Here's how I'm trying to get something to draw right now:
XYPlot plot = chart.getXYPlot();
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
BasicStroke stroke = new BasicStroke(2.0f);
Rectangle2D.Double rect = new Rectangle2D.Double(10, 10, 10, 20);
// renderer.addAnnotation(new XYShapeAnnotation(
// rect, stroke, Color.GREEN), Layer.BACKGROUND);
plot.addAnnotation(new XYShapeAnnotation(
rect, stroke, Color.GREEN));
Ellipse2D.Double circle = new Ellipse2D.Double(8, 8, 20, 20);
renderer.addAnnotation(new XYShapeAnnotation(
circle, stroke, blue), Layer.BACKGROUND);
plot.drawAnnotations((Graphics2D) chartPanel.getGraphics(), chartPanel.getBounds(), chartPanel.getChartRenderingInfo().getPlotInfo());
// This line does draw, but immediately disappears
Graphics2D g2 = (Graphics2D) chartPanel.getGraphics();
Line2D line = new Line2D.Double(0, 100, 500, 350);
g2.draw(line);
Thanks.
Edit with working image:
I think maybe the circle and rectangle I was trying to add are off of the visible chart coordinate space.
It may help to note that org.jfree.chart.annotations typically require that coordinates are specified in model (dataset) coordinates, not view (plot) coordinates.

how to display customized values on a bar in bar chart using jfree chart?

By using StandardCategoryItemLabelGenerator() Iam able to display the exact range axis value on a bar, Now my problem is I dont want to display the range axis value instead I want to display some other value of that bar How I can achieve that?
for (String IDS : idMap.keySet()) {
List<String> listValues = idMap.get(IDS);
if(listValues != null && listValues.get(1) != null) {
dataSet.setValue(Double.valueOf(listValues.get(1)), "", IDS);
}
}
JFreeChart chart = ChartFactory.createBarChart3D("", "", "Time taken ", dataSet,PlotOrientation.VERTICAL, true, true, false);
chart.setTitle(new org.jfree.chart.title.TextTitle("Time Duration",new java.awt.Font("SansSerif", java.awt.Font.BOLD, 10)));
chart.getLegend().setItemFont(new java.awt.Font("SansSerif",0,7));
chart.removeLegend();
final CategoryPlot plot = chart.getCategoryPlot();
plot.setNoDataMessage("No data available");
final CategoryItemRenderer renderer = plot.getRenderer();
renderer.setItemLabelsVisible(true);
final BarRenderer r = (BarRenderer) renderer;
r.setMaximumBarWidth(0.05);
r.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
r.setBaseItemLabelsVisible(true);
r.setSeriesItemLabelFont(0, new java.awt.Font("Times New Roman",Font.NORMAL,7));
r.setSeriesPositiveItemLabelPosition(0,
new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.BOTTOM_LEFT, TextAnchor.BOTTOM_LEFT, -Math.PI/2));
final ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setLabelFont(new java.awt.Font("SansSerif", java.awt.Font.BOLD, 8));
final CategoryAxis axis = plot.getDomainAxis();
axis.setLabel("ids");
axis.setLabelFont(new java.awt.Font("SansSerif", java.awt.Font.BOLD, 8));
axis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 8.0));
axis.setTickLabelFont(new java.awt.Font("SansSerif", java.awt.Font.BOLD, 6));
plot.setDomainGridlinesVisible(true);
plot.setRangeGridlinesVisible(true);
By using the above code iam able to display exact range axis value on a bar, but I dont want the range axis value I need some other value listValues.get(2) to be displayed on a bar How I can achieve that?
StandardCategoryItemLabelGenerator uses an instance of MessgeFormat for this, defaulting to ArgumentIndex {2}. The other ArgumentIndex values are defined in the abstract parent. For example,
renderer.setBaseItemLabelGenerator(
new StandardCategoryItemLabelGenerator(
"{0} {1} {2} {3}", NumberFormat.getInstance()));
renderer.setBaseItemLabelsVisible(true);
You can also override generateLabel() to return any value you want.
renderer.setBaseItemLabelGenerator(
new StandardCategoryItemLabelGenerator()
#Override
public String generateLabel(CategoryDataset dataset, int row, int column) {
return "Your Text" +row+","+column;
}
);

Jfree Using custom names to categories

I'm very new to Jfreechart, Please help me to get the solution for this, I'm using jfree to draw a graph for a categories which has specific code names like 563,258.855,etc... So i want to assign these values as labels to the domain axis, but by default it is assigning value1,value2,value3,etc... to categories.
But I wan to make it something like below
and here is my code,
final CategoryDataset dataset1 = DatasetUtilities.createCategoryDataset("Month to Date Occurences","value", data);
JFreeChart dualchart = ChartFactory.createBarChart(
"Top Ten Diagnostic Occurences", // chart title
"Category", // domain axis label
"Score", // range axis label
dataset1, // data
PlotOrientation.HORIZONTAL, // orientation
true, // include legend
true,
false
);
CategoryPlot plot = dualchart.getCategoryPlot();
plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
plot.setBackgroundPaint(Color.WHITE);
plot.setRangeGridlinePaint(Color.black);
BarRenderer renderer= (BarRenderer) plot.getRenderer();
renderer.setItemMargin(0.0);
CategoryAxis domainAxis = plot.getDomainAxis ();
domainAxis.setCategoryMargin(0.30); //distance between series
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setRange(0.0, 100.0);
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
return dualchart;
Your suggestions are most welcome,
Thanks in advance.
You haven't included the code for dataset1 so it's hard to tell what the problem is but if you use something like this:
private static CategoryDataset createDataset() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(15, "1", "451");
dataset.addValue(12, "1", "851");
dataset.addValue(10, "2", "362");
dataset.addValue(5, "2", "142");
return dataset;
}
You will get a chart like this:

JFreeChart How create an areachart with an TimeLine axis

I want to make the example of jfreechart: XYAreaChartDemo2.java, an xyareachart but the X axis must be of timeSeries. i have tried this:
TimeSeriesCollection dataset1 = new TimeSeriesCollection(timeSeries);//my timeseries
XYSeriesCollection dataset2 = new XYSeriesCollection();
JFreeChart chart = ChartFactory.createXYAreaChart("titulo","Eje x","eje Y", dataset2, PlotOrientation.VERTICAL,true, false,false);
chart.setBackgroundPaint(Color.white);
XYPlot xyplot= chart.getXYPlot();
//fondo
xyplot.setBackgroundPaint(Color.white);
//pone la serie de time en el formato area (pero pierde el formato tiempo)
xyplot.setDataset(dataset1);
but my chart is returned like a areachart with x-axis from 0 to 1.285......
I have a recommended solution here.
Don't limit your mind on making XYAreaChart with TimeSeries X axis. Why not make a TimeSeries chart and render it into XYAreaChart?
Here is how it can be done.
// Create TimeSeriesChart
JFreeChart localJFreeChart = createChart(createDataset());
// Set to be XYAreaChart
XYItemRenderer render = new XYAreaRenderer();
XYPlot plot = localJFreeChart.getXYPlot();
plot.setRenderer(render);
in which
private static JFreeChart createChart(XYDataset paramXYDataset) {
JFreeChart localJFreeChart = ChartFactory.createTimeSeriesChart("Legal & General Unit Trust Prices", "Date", "Price Per Unit", paramXYDataset, true, true, false);
// ...
return (JFreeChart) localJFreeChart;
}
Full code can be seen here.
Most of the code is from TimeSeriesDemo1 in JFreeChart-1.0.14-demo.jar, and modified by myself to meet your requirements.
Hope this could help.
I'm assuming you're using TimeSeries and adding instances of RegularTimePeriod to the data set. By default, the method ChartFactory. createXYAreaChart() uses a NumberAxis for the domain. Instead, use a DateAxis.
XYPlot plot = chart.getXYPlot();
DateAxis domain = new DateAxis("Tiempo");
plot.setDomainAxis(domain);

Jfreechart get Mouse Co-ordinates

I have been trying to get current Mouse Co-ordinates in a JfreeChart and found that the following solution was working partially
JFreeChart get mouse coordinates
I have been using OHLC Dataset to draw the chart and while I could get the RangeAxis properly (meaning in the subplot values), I couldn't make anything out of the value recieved for the X-Axis from the above example.
I am sure that I am receiving the values in some other format (not the displayed date format), anyone could point out what I am doing wrong?
Got it solved after few hours of experiment. Here is the code for a complete MouseMotionListener. Just added this to the chartPanel and voila! - it works!
The chartY returns proper value of Y-Axis and the dateString returns complete date. Tried it in an OHLC Chart and seems proper.
MouseMotionListener mouselisten = new MouseMotionListener() {
public void mouseDragged(MouseEvent e) {
//
}
public void mouseMoved(MouseEvent e) {
Point2D p = e.getPoint();
Rectangle2D plotArea = chartPanel.getScreenDataArea();
XYPlot plot = (XYPlot) chart.getPlot(); // your plot
double chartX = plot.getDomainAxis().java2DToValue(p.getX(), plotArea, plot.getDomainAxisEdge());
double chartY = plot.getRangeAxis().java2DToValue(p.getY(), plotArea, plot.getRangeAxisEdge());
DecimalFormat dfT = new DecimalFormat("00");
GregorianCalendar gc = new GregorianCalendar();
long lDte = (long)chartX;
Date dtXX = new Date(lDte);
gc.setTime(dtXX);
String sDD = dfT.format(Double.valueOf(String.valueOf(gc.get(GregorianCalendar.DAY_OF_MONTH))));
String sMM = dfT.format(Double.valueOf(String.valueOf(gc.get(GregorianCalendar.MONTH)+1)));
String sYY = dfT.format(Double.valueOf(String.valueOf(gc.get(GregorianCalendar.YEAR))));
String dateString = sDD +"/"+ sMM +"/"+ sYY;
}
};

Resources