Example usage for org.jfree.chart JFreeChart addSubtitle

List of usage examples for org.jfree.chart JFreeChart addSubtitle

Introduction

In this page you can find the example usage for org.jfree.chart JFreeChart addSubtitle.

Prototype

public void addSubtitle(Title subtitle) 

Source Link

Document

Adds a chart subtitle, and notifies registered listeners that the chart has been modified.

Usage

From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.OverlaidBarLine.java

public JFreeChart createChart(DatasetMap datasets) {
    logger.debug("IN");

    // create the first renderer...

    CategoryPlot plot = new CategoryPlot();

    NumberFormat nf = NumberFormat.getNumberInstance(locale);

    NumberAxis rangeAxis = new NumberAxis(getValueLabel());
    rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setLabelPaint(styleXaxesLabels.getColor());
    rangeAxis//from w  ww .  j a  v  a2 s  .co m
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor());
    //      rangeAxis.setLowerBound(600);
    //      rangeAxis.setUpperBound(720);
    if (firstAxisLB != null && firstAxisUB != null) {
        rangeAxis.setLowerBound(firstAxisLB);
        rangeAxis.setUpperBound(firstAxisUB);
    }

    rangeAxis.setUpperMargin(0.10);
    plot.setRangeAxis(0, rangeAxis);
    if (rangeIntegerValues == true) {
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }
    rangeAxis.setNumberFormatOverride(nf);

    CategoryAxis domainAxis = new CategoryAxis(getCategoryLabel());
    domainAxis.setLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setLabelPaint(styleYaxesLabels.getColor());
    domainAxis
            .setTickLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setTickLabelPaint(styleYaxesLabels.getColor());
    domainAxis.setUpperMargin(0.10);
    plot.setDomainAxis(domainAxis);

    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setRangeGridlinesVisible(true);
    plot.setDomainGridlinesVisible(true);

    DefaultCategoryDataset datasetLineFirstAxis = (DefaultCategoryDataset) datasets.getDatasets().get("1-line");
    DefaultCategoryDataset datasetBarFirstAxis = (DefaultCategoryDataset) datasets.getDatasets().get("1-bar");
    DefaultCategoryDataset datasetLineSecondAxis = (DefaultCategoryDataset) datasets.getDatasets()
            .get("2-line");
    DefaultCategoryDataset datasetBarSecondAxis = (DefaultCategoryDataset) datasets.getDatasets().get("2-bar");

    //I create one bar renderer and one line
    MyStandardCategoryItemLabelGenerator generator = null;

    // value labels and additional values are mutually exclusive
    if (showValueLabels == true)
        additionalLabels = false;

    if (additionalLabels) {
        generator = new MyStandardCategoryItemLabelGenerator(catSerLabels, "{1}", NumberFormat.getInstance());
    }

    if (useBars) {

        CategoryItemRenderer barRenderer = null;
        if (stackedBarRenderer_1 == true) {
            barRenderer = new StackedBarRenderer();
        } else {
            barRenderer = new BarRenderer();
        }

        CategoryItemRenderer barRenderer2 = new BarRenderer();

        if (stackedBarRenderer_2 == true) {
            barRenderer2 = new StackedBarRenderer();
        } else {
            barRenderer2 = new BarRenderer();
        }

        if (maxBarWidth != null) {
            ((BarRenderer) barRenderer).setMaximumBarWidth(maxBarWidth.doubleValue());
            ((BarRenderer) barRenderer2).setMaximumBarWidth(maxBarWidth.doubleValue());
        }

        if (showValueLabels) {
            barRenderer.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
            barRenderer.setBaseItemLabelsVisible(true);
            barRenderer.setBaseItemLabelFont(
                    new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
            barRenderer.setBaseItemLabelPaint(styleValueLabels.getColor());

            //            barRenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
            //                  ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
            //
            //            barRenderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(
            //                  ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));

            if (valueLabelsPosition.equalsIgnoreCase("inside")) {
                barRenderer.setBasePositiveItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
                barRenderer.setBaseNegativeItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
            } else {
                barRenderer.setBasePositiveItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
                barRenderer.setBaseNegativeItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
            }

        } else if (additionalLabels) {
            barRenderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());
            barRenderer.setBaseItemLabelGenerator(generator);
            double orient = (-Math.PI / 2.0);
            if (styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) {
                orient = 0.0;
            }

            barRenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));
            barRenderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));
            barRenderer.setBaseItemLabelFont(
                    new Font(defaultLabelsStyle.getFontName(), Font.PLAIN, defaultLabelsStyle.getSize()));
            barRenderer.setBaseItemLabelPaint(defaultLabelsStyle.getColor());
            barRenderer.setBaseItemLabelsVisible(true);
        }

        if (showValueLabels) {
            barRenderer2.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
            barRenderer2.setBaseItemLabelsVisible(true);
            barRenderer2.setBaseItemLabelFont(
                    new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
            barRenderer2.setBaseItemLabelPaint(styleValueLabels.getColor());

            //            barRenderer2.setBasePositiveItemLabelPosition(new ItemLabelPosition(
            //                  ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
            //
            //            barRenderer2.setBaseNegativeItemLabelPosition(new ItemLabelPosition(
            //                  ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));

            if (valueLabelsPosition.equalsIgnoreCase("inside")) {
                barRenderer2.setBasePositiveItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
                barRenderer2.setBaseNegativeItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
            } else {
                barRenderer2.setBasePositiveItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
                barRenderer2.setBaseNegativeItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
            }

        } else if (additionalLabels) {
            barRenderer2.setBaseItemLabelGenerator(generator);
            double orient = (-Math.PI / 2.0);
            if (styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) {
                orient = 0.0;
            }

            barRenderer2.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));
            barRenderer2.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));

            barRenderer2.setBaseItemLabelFont(
                    new Font(defaultLabelsStyle.getFontName(), Font.PLAIN, defaultLabelsStyle.getSize()));
            barRenderer2.setBaseItemLabelPaint(defaultLabelsStyle.getColor());
            barRenderer2.setBaseItemLabelsVisible(true);

        }

        if (colorMap != null) {
            int idx = -1;
            for (Iterator iterator = datasetBarFirstAxis.getRowKeys().iterator(); iterator.hasNext();) {
                idx++;
                String serName = (String) iterator.next();
                String labelName = "";
                int index = -1;

                if (seriesCaptions != null && seriesCaptions.size() > 0) {
                    labelName = serName;
                    serName = (String) seriesCaptions.get(serName);
                    index = datasetBarFirstAxis.getRowIndex(labelName);
                } else
                    index = datasetBarFirstAxis.getRowIndex(serName);

                Color color = (Color) colorMap.get(serName);
                if (color != null) {
                    barRenderer.setSeriesPaint(index, color);
                }
            }
            for (Iterator iterator = datasetBarSecondAxis.getRowKeys().iterator(); iterator.hasNext();) {
                idx++;
                String serName = (String) iterator.next();
                String labelName = "";
                int index = -1;

                if (seriesCaptions != null && seriesCaptions.size() > 0) {
                    labelName = serName;
                    serName = (String) seriesCaptions.get(serName);
                    index = datasetBarSecondAxis.getRowIndex(labelName);
                } else
                    index = datasetBarSecondAxis.getRowIndex(serName);

                Color color = (Color) colorMap.get(serName);
                if (color != null) {
                    barRenderer2.setSeriesPaint(index, color);
                    /* test con un renderer
                    if (idx > index){
                       index = idx+1;
                    }
                            
                    barRenderer.setSeriesPaint(index, color);*/
                }
            }
        }
        // add tooltip if enabled
        if (enableToolTips) {
            MyCategoryToolTipGenerator generatorToolTip = new MyCategoryToolTipGenerator(freeToolTips,
                    seriesTooltip, categoriesTooltip, seriesCaptions);
            barRenderer.setToolTipGenerator(generatorToolTip);
            barRenderer2.setToolTipGenerator(generatorToolTip);
        }
        //defines url for drill
        boolean document_composition = false;
        if (mode.equalsIgnoreCase(SpagoBIConstants.DOCUMENT_COMPOSITION))
            document_composition = true;

        logger.debug("Calling Url Generation");

        MyCategoryUrlGenerator mycatUrl = null;
        if (super.rootUrl != null) {
            logger.debug("Set MycatUrl");
            mycatUrl = new MyCategoryUrlGenerator(super.rootUrl);

            mycatUrl.setDocument_composition(document_composition);
            mycatUrl.setCategoryUrlLabel(super.categoryUrlName);
            mycatUrl.setSerieUrlLabel(super.serieUrlname);
            mycatUrl.setDrillDocTitle(drillDocTitle);
            mycatUrl.setTarget(target);
        }
        if (mycatUrl != null
                && (!mycatUrl.getCategoryUrlLabel().equals("") || !mycatUrl.getSerieUrlLabel().equals(""))) {
            barRenderer.setItemURLGenerator(mycatUrl);
            barRenderer2.setItemURLGenerator(mycatUrl);
        }

        plot.setDataset(2, datasetBarFirstAxis);
        plot.setDataset(3, datasetBarSecondAxis);

        plot.setRenderer(2, barRenderer);
        plot.setRenderer(3, barRenderer2);

    }

    if (useLines) {

        LineAndShapeRenderer lineRenderer = new LineAndShapeRenderer();
        LineAndShapeRenderer lineRenderer2 = new LineAndShapeRenderer();

        //lineRenderer.setShapesFilled(false);
        lineRenderer.setShapesFilled(true);
        lineRenderer2.setShapesFilled(true);

        // no shapes for line_no_shapes  series
        for (Iterator iterator = lineNoShapeSeries1.iterator(); iterator.hasNext();) {
            String ser = (String) iterator.next();
            // if there iS a abel associated search for that

            String label = null;
            if (seriesLabelsMap != null) {
                label = (String) seriesLabelsMap.get(ser);
            }
            if (label == null)
                label = ser;
            int index = datasetLineFirstAxis.getRowIndex(label);
            if (index != -1) {
                lineRenderer.setSeriesShapesVisible(index, false);
            }
        }

        for (Iterator iterator = lineNoShapeSeries2.iterator(); iterator.hasNext();) {
            String ser = (String) iterator.next();
            // if there iS a abel associated search for that
            String label = null;
            if (seriesLabelsMap != null) {
                label = (String) seriesLabelsMap.get(ser);
            }
            if (label == null)
                label = ser;
            int index = datasetLineSecondAxis.getRowIndex(label);
            if (index != -1) {
                lineRenderer2.setSeriesShapesVisible(index, false);
            }
        }

        if (enableToolTips) {
            MyCategoryToolTipGenerator generatorToolTip = new MyCategoryToolTipGenerator(freeToolTips,
                    seriesTooltip, categoriesTooltip, seriesCaptions);
            lineRenderer.setToolTipGenerator(generatorToolTip);
            lineRenderer2.setToolTipGenerator(generatorToolTip);
        }

        if (showValueLabels) {
            lineRenderer.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
            lineRenderer.setBaseItemLabelsVisible(true);
            lineRenderer.setBaseItemLabelFont(
                    new Font(styleValueLabels.getFontName(), Font.ITALIC, styleValueLabels.getSize()));
            lineRenderer.setBaseItemLabelPaint(styleValueLabels.getColor());

            lineRenderer.setBasePositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_RIGHT));

            lineRenderer.setBaseNegativeItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_RIGHT));

        } else if (additionalLabels) {
            lineRenderer.setBaseItemLabelGenerator(generator);
            lineRenderer.setBaseItemLabelFont(
                    new Font(defaultLabelsStyle.getFontName(), Font.PLAIN, defaultLabelsStyle.getSize()));
            lineRenderer.setBaseItemLabelPaint(defaultLabelsStyle.getColor());
            lineRenderer.setBaseItemLabelsVisible(true);
        }

        if (showValueLabels) {
            lineRenderer2.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
            lineRenderer2.setBaseItemLabelsVisible(true);
            lineRenderer2.setBaseItemLabelFont(
                    new Font(styleValueLabels.getFontName(), Font.ITALIC, styleValueLabels.getSize()));
            lineRenderer2.setBaseItemLabelPaint(styleValueLabels.getColor());

            lineRenderer2.setBasePositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_RIGHT));

            lineRenderer2.setBaseNegativeItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_RIGHT));

        } else if (additionalLabels) {
            lineRenderer2.setBaseItemLabelGenerator(generator);
            lineRenderer2.setBaseItemLabelFont(
                    new Font(defaultLabelsStyle.getFontName(), Font.PLAIN, defaultLabelsStyle.getSize()));
            lineRenderer2.setBaseItemLabelPaint(defaultLabelsStyle.getColor());
            lineRenderer2.setBaseItemLabelsVisible(true);
        }

        //         DefaultCategoryDataset datasetSecondAxis=(DefaultCategoryDataset)datasets.getDatasets().get("2");

        if (colorMap != null) {
            for (Iterator iterator = datasetLineSecondAxis.getRowKeys().iterator(); iterator.hasNext();) {
                String serName = (String) iterator.next();
                String labelName = "";
                int index = -1;

                if (seriesCaptions != null && seriesCaptions.size() > 0) {
                    labelName = serName;
                    serName = (String) seriesCaptions.get(serName);
                    index = datasetLineSecondAxis.getRowIndex(labelName);
                } else
                    index = datasetLineSecondAxis.getRowIndex(serName);

                Color color = (Color) colorMap.get(serName);
                if (color != null) {
                    lineRenderer2.setSeriesPaint(index, color);
                }
            }
            for (Iterator iterator = datasetLineFirstAxis.getRowKeys().iterator(); iterator.hasNext();) {
                String serName = (String) iterator.next();
                String labelName = "";
                int index = -1;

                if (seriesCaptions != null && seriesCaptions.size() > 0) {
                    labelName = serName;
                    serName = (String) seriesCaptions.get(serName);
                    index = datasetLineFirstAxis.getRowIndex(labelName);
                } else
                    index = datasetLineFirstAxis.getRowIndex(serName);

                Color color = (Color) colorMap.get(serName);
                if (color != null) {
                    lineRenderer.setSeriesPaint(index, color);
                }
            }

        }
        plot.setDataset(0, datasetLineFirstAxis);
        plot.setRenderer(0, lineRenderer);
        plot.setDataset(1, datasetLineSecondAxis);
        plot.setRenderer(1, lineRenderer2);

    }

    if (secondAxis) {
        NumberAxis na = new NumberAxis(secondAxisLabel);
        na.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
        na.setLabelPaint(styleXaxesLabels.getColor());
        na.setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
        na.setTickLabelPaint(styleXaxesLabels.getColor());
        na.setUpperMargin(0.10);
        na.setNumberFormatOverride(nf);
        //         rangeAxis.setLowerBound(270);
        //         rangeAxis.setUpperBound(340);
        if (secondAxisLB != null && secondAxisUB != null) {
            rangeAxis.setLowerBound(secondAxisLB);
            rangeAxis.setUpperBound(secondAxisUB);
        }
        plot.setRangeAxis(1, na);
        plot.mapDatasetToRangeAxis(0, 0);
        plot.mapDatasetToRangeAxis(2, 0);
        plot.mapDatasetToRangeAxis(1, 1);
        plot.mapDatasetToRangeAxis(3, 1);
        if (rangeIntegerValues == true) {
            na.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        }

    }

    //plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    JFreeChart chart = new JFreeChart(plot);

    TextTitle title = setStyleTitle(name, styleTitle);
    chart.setTitle(title);
    if (subName != null && !subName.equals("")) {
        TextTitle subTitle = setStyleTitle(subName, styleSubTitle);
        chart.addSubtitle(subTitle);
    }
    chart.setBackgroundPaint(Color.white);

    if (legend == true)
        drawLegend(chart);

    logger.debug("OUT");

    return chart;

}

From source file:KIDLYFactory.java

/**
 * Creates a pie chart with default settings that compares 2 datasets.
 * The colour of each section will be determined by the move from the value
 * for the same key in <code>previousDataset</code>. ie if value1 > value2
 * then the section will be in green (unless <code>greenForIncrease</code>
 * is <code>false</code>, in which case it would be <code>red</code>).
 * Each section can have a shade of red or green as the difference can be
 * tailored between 0% (black) and percentDiffForMaxScale% (bright
 * red/green)./*from  w ww. j a va2  s  .  c  o  m*/
 * <p>
 * For instance if <code>percentDiffForMaxScale</code> is 10 (10%), a
 * difference of 5% will have a half shade of red/green, a difference of
 * 10% or more will have a maximum shade/brightness of red/green.
 * <P>
 * The chart object returned by this method uses a {@link PiePlot} instance
 * as the plot.
 * <p>
 * Written by <a href="mailto:opensource@objectlab.co.uk">Benoit
 * Xhenseval</a>.
 *
 * @param title  the chart title (<code>null</code> permitted).
 * @param dataset  the dataset for the chart (<code>null</code> permitted).
 * @param previousDataset  the dataset for the last run, this will be used
 *                         to compare each key in the dataset
 * @param percentDiffForMaxScale scale goes from bright red/green to black,
 *                               percentDiffForMaxScale indicate the change
 *                               required to reach top scale.
 * @param greenForIncrease  an increase since previousDataset will be
 *                          displayed in green (decrease red) if true.
 * @param legend  a flag specifying whether or not a legend is required.
 * @param tooltips  configure chart to generate tool tips?
 * @param locale  the locale (<code>null</code> not permitted).
 * @param subTitle displays a subtitle with colour scheme if true
 * @param showDifference  create a new dataset that will show the %
 *                        difference between the two datasets.
 *
 * @return A pie chart.
 *
 * @since 1.0.7
 */
public static JFreeChart createPieChart(String title, PieDataset dataset, PieDataset previousDataset,
        int percentDiffForMaxScale, boolean greenForIncrease, boolean legend, boolean tooltips, Locale locale,
        boolean subTitle, boolean showDifference) {

    PiePlot plot = new PiePlot(dataset);
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator(locale));
    plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));

    if (tooltips) {
        plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));
    }

    List keys = dataset.getKeys();
    DefaultPieDataset series = null;
    if (showDifference) {
        series = new DefaultPieDataset();
    }

    double colorPerPercent = 255.0 / percentDiffForMaxScale;
    for (Iterator it = keys.iterator(); it.hasNext();) {
        Comparable key = (Comparable) it.next();
        Number newValue = dataset.getValue(key);
        Number oldValue = previousDataset.getValue(key);

        if (oldValue == null) {
            if (greenForIncrease) {
                plot.setSectionPaint(key, Color.green);
            } else {
                plot.setSectionPaint(key, Color.red);
            }
            if (showDifference) {
                series.setValue(key + " (+100%)", newValue);
            }
        } else {
            double percentChange = (newValue.doubleValue() / oldValue.doubleValue() - 1.0) * 100.0;
            double shade = (Math.abs(percentChange) >= percentDiffForMaxScale ? 255
                    : Math.abs(percentChange) * colorPerPercent);
            if (greenForIncrease && newValue.doubleValue() > oldValue.doubleValue()
                    || !greenForIncrease && newValue.doubleValue() < oldValue.doubleValue()) {
                plot.setSectionPaint(key, new Color(0, (int) shade, 0));
            } else {
                plot.setSectionPaint(key, new Color((int) shade, 0, 0));
            }
            if (showDifference) {
                series.setValue(
                        key + " (" + (percentChange >= 0 ? "+" : "")
                                + NumberFormat.getPercentInstance().format(percentChange / 100.0) + ")",
                        newValue);
            }
        }
    }

    if (showDifference) {
        plot.setDataset(series);
    }

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);

    if (subTitle) {
        TextTitle subtitle = null;
        subtitle = new TextTitle("Bright " + (greenForIncrease ? "red" : "green") + "=change >=-"
                + percentDiffForMaxScale + "%, Bright " + (!greenForIncrease ? "red" : "green") + "=change >=+"
                + percentDiffForMaxScale + "%", new Font("SansSerif", Font.PLAIN, 10));
        chart.addSubtitle(subtitle);
    }
    currentTheme.apply(chart);
    return chart;
}

From source file:KIDLYFactory.java

/**
 * Creates a pie chart with default settings that compares 2 datasets.
 * The colour of each section will be determined by the move from the value
 * for the same key in <code>previousDataset</code>. ie if value1 > value2
 * then the section will be in green (unless <code>greenForIncrease</code>
 * is <code>false</code>, in which case it would be <code>red</code>).
 * Each section can have a shade of red or green as the difference can be
 * tailored between 0% (black) and percentDiffForMaxScale% (bright
 * red/green).//w w  w  .j a v  a2s.  c  o  m
 * <p>
 * For instance if <code>percentDiffForMaxScale</code> is 10 (10%), a
 * difference of 5% will have a half shade of red/green, a difference of
 * 10% or more will have a maximum shade/brightness of red/green.
 * <P>
 * The chart object returned by this method uses a {@link PiePlot} instance
 * as the plot.
 * <p>
 * Written by <a href="mailto:opensource@objectlab.co.uk">Benoit
 * Xhenseval</a>.
 *
 * @param title  the chart title (<code>null</code> permitted).
 * @param dataset  the dataset for the chart (<code>null</code> permitted).
 * @param previousDataset  the dataset for the last run, this will be used
 *                         to compare each key in the dataset
 * @param percentDiffForMaxScale scale goes from bright red/green to black,
 *                               percentDiffForMaxScale indicate the change
 *                               required to reach top scale.
 * @param greenForIncrease  an increase since previousDataset will be
 *                          displayed in green (decrease red) if true.
 * @param legend  a flag specifying whether or not a legend is required.
 * @param tooltips  configure chart to generate tool tips?
 * @param urls  configure chart to generate URLs?
 * @param subTitle displays a subtitle with colour scheme if true
 * @param showDifference  create a new dataset that will show the %
 *                        difference between the two datasets.
 *
 * @return A pie chart.
 */
public static JFreeChart createPieChart(String title, PieDataset dataset, PieDataset previousDataset,
        int percentDiffForMaxScale, boolean greenForIncrease, boolean legend, boolean tooltips, boolean urls,
        boolean subTitle, boolean showDifference) {

    PiePlot plot = new PiePlot(dataset);
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator());
    plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));

    if (tooltips) {
        plot.setToolTipGenerator(new StandardPieToolTipGenerator());
    }
    if (urls) {
        plot.setURLGenerator(new StandardPieURLGenerator());
    }

    List keys = dataset.getKeys();
    DefaultPieDataset series = null;
    if (showDifference) {
        series = new DefaultPieDataset();
    }

    double colorPerPercent = 255.0 / percentDiffForMaxScale;
    for (Iterator it = keys.iterator(); it.hasNext();) {
        Comparable key = (Comparable) it.next();
        Number newValue = dataset.getValue(key);
        Number oldValue = previousDataset.getValue(key);

        if (oldValue == null) {
            if (greenForIncrease) {
                plot.setSectionPaint(key, Color.green);
            } else {
                plot.setSectionPaint(key, Color.red);
            }
            if (showDifference) {
                series.setValue(key + " (+100%)", newValue);
            }
        } else {
            double percentChange = (newValue.doubleValue() / oldValue.doubleValue() - 1.0) * 100.0;
            double shade = (Math.abs(percentChange) >= percentDiffForMaxScale ? 255
                    : Math.abs(percentChange) * colorPerPercent);
            if (greenForIncrease && newValue.doubleValue() > oldValue.doubleValue()
                    || !greenForIncrease && newValue.doubleValue() < oldValue.doubleValue()) {
                plot.setSectionPaint(key, new Color(0, (int) shade, 0));
            } else {
                plot.setSectionPaint(key, new Color((int) shade, 0, 0));
            }
            if (showDifference) {
                series.setValue(
                        key + " (" + (percentChange >= 0 ? "+" : "")
                                + NumberFormat.getPercentInstance().format(percentChange / 100.0) + ")",
                        newValue);
            }
        }
    }

    if (showDifference) {
        plot.setDataset(series);
    }

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);

    if (subTitle) {
        TextTitle subtitle = null;
        subtitle = new TextTitle("Bright " + (greenForIncrease ? "red" : "green") + "=change >=-"
                + percentDiffForMaxScale + "%, Bright " + (!greenForIncrease ? "red" : "green") + "=change >=+"
                + percentDiffForMaxScale + "%", new Font("SansSerif", Font.PLAIN, 10));
        chart.addSubtitle(subtitle);
    }
    currentTheme.apply(chart);
    return chart;
}

From source file:org.toobsframework.pres.chart.ChartBuilder.java

private JFreeChart finishChart(IRequest componentRequest, ChartDefinition chartDef, Plot plot, Map params) {

    JFreeChart chart = new JFreeChart(
            ChartUtil.evaluateTextLabel(componentRequest, chartDef.getTitle(), params),
            ChartUtil.getFont(chartDef.getTitle(), JFreeChart.DEFAULT_TITLE_FONT), plot,
            chartDef.isShowLegend());/*from   w  ww  .j av a  2  s  .  c  o m*/

    if (chartDef.getSubtitle() != null) {
        TextTitle subtitle = new TextTitle(
                ChartUtil.evaluateTextLabel(componentRequest, chartDef.getSubtitle(), params));
        if (chartDef.getSubtitle().getFont() != null) {
            subtitle.setFont(ChartUtil.getFont(chartDef.getSubtitle(), null));
        }
        subtitle.setPosition(ChartUtil.getPosition(chartDef.getSubtitle().getPosition()));
        subtitle.setPadding(
                ChartUtil.getRectangle(componentRequest, chartDef.getSubtitle().getPadding(), params));
        subtitle.setVerticalAlignment(
                ChartUtil.getVerticalAlignment(chartDef.getSubtitle().getVerticalAlignment()));
        subtitle.setPaint(ChartUtil.getColor(chartDef.getSubtitle().getColor()));
        chart.addSubtitle(subtitle);
    }

    chart.setBackgroundPaint(ChartUtil.getColor(chartDef.getBackgroundColor()));
    if (chartDef.getTitle() != null && chartDef.getTitle().getColor() != null) {
        chart.getTitle().setPaint(ChartUtil.getColor(chartDef.getTitle().getColor()));
    }

    if (chartDef.isShowLegend()) {
        ChartUtil.configureLegend(componentRequest, chart, chartDef.getLegend(), params);
    }

    return chart;
}

From source file:RMOS.PieChart.java

/**
 * Creates a chart./*from   w ww.j a  v a2 s .  c  om*/
 *
 * @param dataset  the dataset.
 *
 * @return A chart.
 */
private static JFreeChart createChart(PieDataset dataset) {

    JFreeChart chart = ChartFactory.createPieChart("Eco Systems Statistics", // chart title
            dataset, // data
            false, // no legend
            true, // tooltips
            false // no URL generation
    );

    // set a custom background for the chart
    chart.setBackgroundPaint(
            new GradientPaint(new Point(0, 0), new Color(20, 20, 20), new Point(400, 200), Color.DARK_GRAY));

    // customise the title position and font
    TextTitle t = chart.getTitle();
    t.setHorizontalAlignment(HorizontalAlignment.LEFT);
    t.setPaint(new Color(240, 240, 240));
    t.setFont(new Font("Arial", Font.BOLD, 26));

    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(null);
    plot.setInteriorGap(0.04);
    plot.setOutlineVisible(false);

    plot.setSectionPaint(f1.getStationInGroup().get(1), Color.blue);
    plot.setSectionPaint(f1.getStationInGroup().get(1), Color.GREEN);

    // use gradients and white borders for the section colours
    /*plot.setSectionPaint("Others", createGradientPaint(new Color(200, 200, 255), Color.BLUE));
    plot.setSectionPaint("Samsung", createGradientPaint(new Color(255, 200, 200), Color.RED));
    plot.setSectionPaint("Apple", createGradientPaint(new Color(200, 255, 200), Color.GREEN));
    plot.setSectionPaint("Nokia", createGradientPaint(new Color(200, 255, 200), Color.YELLOW));*/
    plot.setBaseSectionOutlinePaint(Color.WHITE);
    plot.setSectionOutlinesVisible(true);
    plot.setBaseSectionOutlineStroke(new BasicStroke(2.0f));

    // customise the section label appearance
    plot.setLabelFont(new Font("Courier New", Font.BOLD, 20));
    plot.setLabelLinkPaint(Color.WHITE);
    plot.setLabelLinkStroke(new BasicStroke(2.0f));
    plot.setLabelOutlineStroke(null);
    plot.setLabelPaint(Color.WHITE);
    plot.setLabelBackgroundPaint(null);

    // add a subtitle giving the data source
    TextTitle source = new TextTitle("Source: Eco Recycle Station", new Font("Courier New", Font.PLAIN, 12));
    source.setPaint(Color.WHITE);
    source.setPosition(RectangleEdge.BOTTOM);
    source.setHorizontalAlignment(HorizontalAlignment.RIGHT);
    chart.addSubtitle(source);
    return chart;

}

From source file:charts.PieChart3D.java

/**
 * Creates a chart./* ww  w  .  j  av  a  2  s.c om*/
 *
 * @param dataset
 *            the dataset.
 *
 * @return A chart.
 */
private static JFreeChart createChart(PieDataset dataset, PieChartModel model) {

    JFreeChart chart = ChartFactory.createPieChart(model.getTitle(), // chart
            // title
            dataset, // data
            false, // no legend
            true, // tooltips
            false // no URL generation
    );

    // set a custom background for the chart
    chart.setBackgroundPaint(
            new GradientPaint(new Point(0, 0), new Color(20, 20, 20), new Point(400, 200), Color.DARK_GRAY));

    // customise the title position and font
    TextTitle t = chart.getTitle();
    t.setHorizontalAlignment(HorizontalAlignment.LEFT);
    t.setPaint(new Color(240, 240, 240));
    t.setFont(new Font("Arial", Font.BOLD, 26));

    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(null);
    plot.setInteriorGap(0.04);
    plot.setOutlineVisible(false);

    // use gradients and white borders for the section colours
    plot.setSectionPaint("FCA", createGradientPaint(new Color(200, 200, 255), Color.BLUE));
    plot.setSectionPaint("FCH", createGradientPaint(new Color(255, 200, 200), Color.RED));
    plot.setSectionPaint("FCS", createGradientPaint(new Color(200, 255, 200), Color.GREEN));
    plot.setSectionPaint("FCG", createGradientPaint(new Color(200, 255, 200), Color.YELLOW));
    plot.setSectionPaint("FCJ", createGradientPaint(new Color(200, 255, 200), Color.BLACK));
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} {1} ({2}) "));
    plot.setBaseSectionOutlinePaint(Color.WHITE);
    plot.setSectionOutlinesVisible(true);
    plot.setBaseSectionOutlineStroke(new BasicStroke(2.0f));

    // customise the section label appearance
    plot.setLabelFont(new Font("Courier New", Font.BOLD, 20));
    plot.setLabelLinkPaint(Color.WHITE);
    plot.setLabelLinkStroke(new BasicStroke(2.0f));
    plot.setLabelOutlineStroke(null);
    plot.setLabelPaint(Color.WHITE);
    plot.setLabelBackgroundPaint(null);

    // add a subtitle giving the data source
    TextTitle source = new TextTitle(model.getSubTitle(), new Font("Courier New", Font.PLAIN, 12));
    source.setPaint(Color.WHITE);
    source.setPosition(RectangleEdge.BOTTOM);
    source.setHorizontalAlignment(HorizontalAlignment.RIGHT);
    chart.addSubtitle(source);
    return chart;

}

From source file:org.jfree.chart.demo.CombinedXYPlotDemo5.java

/**
 * Creates a combined XYPlot chart./*from   ww  w.  ja  va 2s  .c  o  m*/
 *
 * @return the combined chart.
 */
private JFreeChart createCombinedChart() {

    // create a default chart based on some sample data...
    final TimeSeriesCollection dataset0 = new TimeSeriesCollection();
    final TimeSeries eur = DemoDatasetFactory.createEURTimeSeries();
    dataset0.addSeries(eur);

    final TimeSeriesCollection dataset1 = new TimeSeriesCollection();
    final TimeSeries mav = MovingAverage.createMovingAverage(eur, "EUR/GBP (30 Day MA)", 30, 30);
    dataset1.addSeries(eur);
    dataset1.addSeries(mav);

    final TimeSeriesCollection dataset2 = new TimeSeriesCollection();
    dataset2.addSeries(eur);

    JFreeChart chart = null;

    // make a common vertical axis for all the sub-plots
    final NumberAxis valueAxis = new NumberAxis("Value");
    valueAxis.setAutoRangeIncludesZero(false); // override default

    // make a horizontally combined plot
    final CombinedRangeXYPlot parent = new CombinedRangeXYPlot(valueAxis);

    // add subplot 1...
    final XYPlot subplot1 = new XYPlot(dataset0, new DateAxis("Date 1"), null, new StandardXYItemRenderer());
    subplot1.setDomainCrosshairVisible(true);
    subplot1.setRangeCrosshairVisible(true);
    parent.add(subplot1, 1);

    // add subplot 2...
    final XYPlot subplot2 = new XYPlot(dataset1, new DateAxis("Date 2"), null, new StandardXYItemRenderer());
    subplot2.setDomainCrosshairVisible(true);
    subplot2.setRangeCrosshairVisible(true);
    parent.add(subplot2, 1);

    // add subplot 3...
    final XYPlot subplot3 = new XYPlot(dataset2, new DateAxis("Date 3"), null, new XYBarRenderer(0.20));
    subplot3.setDomainCrosshairVisible(true);
    subplot3.setRangeCrosshairVisible(true);
    parent.add(subplot3, 1);

    // now make the top level JFreeChart
    chart = new JFreeChart("Demo Chart", JFreeChart.DEFAULT_TITLE_FONT, parent, true);

    // then customise it a little...
    final TextTitle subtitle = new TextTitle("This is a subtitle", new Font("SansSerif", Font.BOLD, 12));
    chart.addSubtitle(subtitle);
    chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 0, 1000, Color.blue));
    return chart;

}

From source file:org.openmrs.web.servlet.ShowGraphServlet.java

/**
 * The main method for this class. It will create a JFreeChart object to be written to the
 * response./*from  w  w  w.j av  a2s  .  com*/
 *
 * @param request the current request will all the parameters needed
 * @return JFreeChart object to be rendered
 * @should set value axis label to given units
 * @should set value axis label to concept numeric units if given units is null
 */
protected JFreeChart getChart(HttpServletRequest request) {
    // All available GET parameters
    String patientId = request.getParameter("patientId"); // required
    String conceptId1 = request.getParameter("conceptId"); // required
    String conceptId2 = request.getParameter("conceptId2");
    String chartTitle = request.getParameter("chartTitle");
    String units = request.getParameter("units");

    String minRangeString = request.getParameter("minRange");
    String maxRangeString = request.getParameter("maxRange");

    String hideDate = request.getParameter("hideDate");

    Patient patient = Context.getPatientService().getPatient(Integer.parseInt(patientId));

    // Set date range to passed values, otherwise set a default date range to the last 12 months
    Calendar cal = Calendar.getInstance();
    Date fromDate = getFromDate(request.getParameter("fromDate"));
    Date toDate = getToDate(request.getParameter("toDate"));

    // Swap if fromDate is after toDate
    if (fromDate.getTime() > toDate.getTime()) {
        Long temp = fromDate.getTime();
        fromDate.setTime(toDate.getTime());
        toDate.setTime(temp);
    }

    // Graph parameters
    Double minRange = null;
    Double maxRange = null;
    Double normalLow = null;
    Double normalHigh = null;
    Double criticalLow = null;
    Double criticalHigh = null;
    String timeAxisTitle = null;
    String rangeAxisTitle = null;
    boolean userSpecifiedMaxRange = false;
    boolean userSpecifiedMinRange = false;

    // Fetching obs
    List<Obs> observations1 = new ArrayList<Obs>();
    List<Obs> observations2 = new ArrayList<Obs>();
    Concept concept1 = null, concept2 = null;
    if (conceptId1 != null) {
        concept1 = Context.getConceptService().getConcept(Integer.parseInt(conceptId1));
    }
    if (conceptId2 != null) {
        concept2 = Context.getConceptService().getConcept(Integer.parseInt(conceptId2));
    }
    if (concept1 != null) {
        observations1 = Context.getObsService().getObservationsByPersonAndConcept(patient, concept1);
        chartTitle = concept1.getName().getName();
        rangeAxisTitle = ((ConceptNumeric) concept1).getUnits();
        minRange = ((ConceptNumeric) concept1).getLowAbsolute();
        maxRange = ((ConceptNumeric) concept1).getHiAbsolute();
        normalLow = ((ConceptNumeric) concept1).getLowNormal();
        normalHigh = ((ConceptNumeric) concept1).getHiNormal();
        criticalLow = ((ConceptNumeric) concept1).getLowCritical();
        criticalHigh = ((ConceptNumeric) concept1).getHiCritical();

        // Only get observations2 if both concepts share the same units; update chart title and ranges
        if (concept2 != null) {
            String concept2Units = ((ConceptNumeric) concept2).getUnits();
            if (concept2Units != null && concept2Units.equals(rangeAxisTitle)) {
                observations2 = Context.getObsService().getObservationsByPersonAndConcept(patient, concept2);
                chartTitle += " + " + concept2.getName().getName();
                if (((ConceptNumeric) concept2).getHiAbsolute() != null
                        && ((ConceptNumeric) concept2).getHiAbsolute() > maxRange) {
                    maxRange = ((ConceptNumeric) concept2).getHiAbsolute();
                }
                if (((ConceptNumeric) concept2).getLowAbsolute() != null
                        && ((ConceptNumeric) concept2).getLowAbsolute() < minRange) {
                    minRange = ((ConceptNumeric) concept2).getLowAbsolute();
                }
            } else {
                log.warn("Units for concept id: " + conceptId2 + " don't match units for concept id: "
                        + conceptId1 + ". Only displaying " + conceptId1);
                concept2 = null; // nullify concept2 so that the legend isn't shown later
            }
        }
    } else {
        chartTitle = "Concept " + conceptId1 + " not found";
        rangeAxisTitle = "Value";
    }

    // Overwrite with user-specified values, otherwise use default values
    if (units != null && units.length() > 0) {
        rangeAxisTitle = units;
    }
    if (minRangeString != null) {
        minRange = Double.parseDouble(minRangeString);
        userSpecifiedMinRange = true;
    }
    if (maxRangeString != null) {
        maxRange = Double.parseDouble(maxRangeString);
        userSpecifiedMaxRange = true;
    }
    if (chartTitle == null) {
        chartTitle = "";
    }
    if (rangeAxisTitle == null) {
        rangeAxisTitle = "";
    }
    if (minRange == null) {
        minRange = 0.0;
    }
    if (maxRange == null) {
        maxRange = 200.0;
    }

    // Create data set
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    TimeSeries series1, series2;

    // Interval-dependent units
    Class<? extends RegularTimePeriod> timeScale = null;
    if (toDate.getTime() - fromDate.getTime() <= 86400000) {
        // Interval <= 1 day: minutely
        timeScale = Minute.class;
        timeAxisTitle = "Time";
    } else if (toDate.getTime() - fromDate.getTime() <= 259200000) {
        // Interval <= 3 days: hourly
        timeScale = Hour.class;
        timeAxisTitle = "Time";
    } else {
        timeScale = Day.class;
        timeAxisTitle = "Date";
    }
    if (concept1 == null) {
        series1 = new TimeSeries("NULL", Hour.class);
    } else {
        series1 = new TimeSeries(concept1.getName().getName(), timeScale);
    }
    if (concept2 == null) {
        series2 = new TimeSeries("NULL", Hour.class);
    } else {
        series2 = new TimeSeries(concept2.getName().getName(), timeScale);
    }

    // Add data points for concept1
    for (Obs obs : observations1) {
        if (obs.getValueNumeric() != null && obs.getObsDatetime().getTime() >= fromDate.getTime()
                && obs.getObsDatetime().getTime() < toDate.getTime()) {
            cal.setTime(obs.getObsDatetime());
            if (timeScale == Minute.class) {
                Minute min = new Minute(cal.get(Calendar.MINUTE), cal.get(Calendar.HOUR_OF_DAY),
                        cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
                series1.addOrUpdate(min, obs.getValueNumeric());
            } else if (timeScale == Hour.class) {
                Hour hour = new Hour(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.DAY_OF_MONTH),
                        cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
                series1.addOrUpdate(hour, obs.getValueNumeric());
            } else {
                Day day = new Day(cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1,
                        cal.get(Calendar.YEAR));
                series1.addOrUpdate(day, obs.getValueNumeric());
            }
        }
    }

    // Add data points for concept2
    for (Obs obs : observations2) {
        if (obs.getValueNumeric() != null && obs.getObsDatetime().getTime() >= fromDate.getTime()
                && obs.getObsDatetime().getTime() < toDate.getTime()) {
            cal.setTime(obs.getObsDatetime());
            if (timeScale == Minute.class) {
                Minute min = new Minute(cal.get(Calendar.MINUTE), cal.get(Calendar.HOUR_OF_DAY),
                        cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
                series2.addOrUpdate(min, obs.getValueNumeric());
            } else if (timeScale == Hour.class) {
                Hour hour = new Hour(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.DAY_OF_MONTH),
                        cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR));
                series2.addOrUpdate(hour, obs.getValueNumeric());
            } else {
                Day day = new Day(cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1,
                        cal.get(Calendar.YEAR));
                series2.addOrUpdate(day, obs.getValueNumeric());
            }
        }
    }

    // Add series to dataset
    dataset.addSeries(series1);
    if (!series2.isEmpty()) {
        dataset.addSeries(series2);
    }

    // As of JFreeChart 1.0.11 the default background color is dark grey instead of white.
    // This line restores the original white background.
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());

    JFreeChart chart = null;

    // Show legend only if more than one series
    if (concept2 == null) {
        chart = ChartFactory.createTimeSeriesChart(chartTitle, timeAxisTitle, rangeAxisTitle, dataset, false,
                false, false);
    } else {
        chart = ChartFactory.createTimeSeriesChart(chartTitle, timeAxisTitle, rangeAxisTitle, dataset, true,
                false, false);
    }

    // Customize title font
    Font font = new Font("Arial", Font.BOLD, 12);
    TextTitle title = chart.getTitle();
    title.setFont(font);
    chart.setTitle(title);

    // Add subtitle, unless 'hideDate' has been passed
    if (hideDate == null) {
        TextTitle subtitle = new TextTitle(fromDate.toString() + " - " + toDate.toString());
        subtitle.setFont(font);
        chart.addSubtitle(subtitle);
    }

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setNoDataMessage("No Data Available");

    // Add abnormal/critical range background color (only for single-concept graphs)
    if (concept2 == null) {
        IntervalMarker abnormalLow, abnormalHigh, critical;
        if (normalHigh != null) {
            abnormalHigh = new IntervalMarker(normalHigh, maxRange, COLOR_ABNORMAL);
            plot.addRangeMarker(abnormalHigh);
        }
        if (normalLow != null) {
            abnormalLow = new IntervalMarker(minRange, normalLow, COLOR_ABNORMAL);
            plot.addRangeMarker(abnormalLow);
        }
        if (criticalHigh != null) {
            critical = new IntervalMarker(criticalHigh, maxRange, COLOR_CRITICAL);
            plot.addRangeMarker(critical);
        }
        if (criticalLow != null) {
            critical = new IntervalMarker(minRange, criticalLow, COLOR_CRITICAL);
            plot.addRangeMarker(critical);
        }

        // there is data outside of the absolute lower limits for this concept (or of what the user specified as minrange)
        if (plot.getRangeAxis().getLowerBound() < minRange) {
            IntervalMarker error = new IntervalMarker(plot.getRangeAxis().getLowerBound(), minRange,
                    COLOR_ERROR);
            plot.addRangeMarker(error);
        }

        if (plot.getRangeAxis().getUpperBound() > maxRange) {
            IntervalMarker error = new IntervalMarker(maxRange, plot.getRangeAxis().getUpperBound(),
                    COLOR_ERROR);
            plot.addRangeMarker(error);
        }

    }

    // Visuals
    XYItemRenderer r = plot.getRenderer();
    if (r instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
        renderer.setBaseShapesFilled(true);
        renderer.setBaseShapesVisible(true);
    }

    // Customize the plot (range and domain axes)

    // Modify x-axis (datetime)
    DateAxis timeAxis = (DateAxis) plot.getDomainAxis();
    if (timeScale == Day.class) {
        timeAxis.setDateFormatOverride(new SimpleDateFormat("dd-MMM-yyyy"));
    }

    timeAxis.setRange(fromDate, toDate);

    // Set y-axis range (values)
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    if (userSpecifiedMinRange) {
        minRange = (rangeAxis.getLowerBound() < minRange) ? rangeAxis.getLowerBound() : minRange;
    }

    if (userSpecifiedMaxRange) {
        // otherwise we just use default range
        maxRange = (rangeAxis.getUpperBound() > maxRange) ? rangeAxis.getUpperBound() : maxRange;
    }

    rangeAxis.setRange(minRange, maxRange);

    return chart;
}

From source file:org.jfree.chart.demo.AnnotationDemo2.java

private static JFreeChart createChart() {
    XYDataset xydataset = createDataset1();
    JFreeChart jfreechart = ChartFactory.createXYLineChart("Annotation Demo 2", "Date", "Price Per Unit",
            xydataset, PlotOrientation.VERTICAL, false, true, false);
    XYPlot xyplot = (XYPlot) jfreechart.getPlot();
    NumberAxis numberaxis = (NumberAxis) xyplot.getRangeAxis();
    numberaxis.setAutoRangeIncludesZero(false);
    NumberAxis numberaxis1 = new NumberAxis("Secondary");
    numberaxis1.setAutoRangeIncludesZero(false);
    xyplot.setRangeAxis(1, numberaxis1);
    xyplot.setDataset(1, createDataset2());
    xyplot.mapDatasetToRangeAxis(1, 1);/*from   w ww.ja  v a 2s . com*/
    XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyplot.getRenderer();
    xylineandshaperenderer.setBaseToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());
    xylineandshaperenderer.setBaseShapesVisible(true);
    xylineandshaperenderer.setBaseShapesFilled(true);
    XYPointerAnnotation xypointerannotation = new XYPointerAnnotation("Annotation 1 (2.0, 167.3)", 2D,
            167.30000000000001D, -0.78539816339744828D);
    xypointerannotation.setTextAnchor(TextAnchor.BOTTOM_LEFT);
    xypointerannotation.setPaint(Color.red);
    xypointerannotation.setArrowPaint(Color.red);
    xylineandshaperenderer.addAnnotation(xypointerannotation);
    XYLineAndShapeRenderer xylineandshaperenderer1 = new XYLineAndShapeRenderer(true, true);
    xylineandshaperenderer1.setSeriesPaint(0, Color.black);
    xylineandshaperenderer.setBaseToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());
    XYPointerAnnotation xypointerannotation1 = new XYPointerAnnotation("Annotation 2 (15.0, 613.2)", 15D,
            613.20000000000005D, 1.5707963267948966D);
    xypointerannotation1.setTextAnchor(TextAnchor.TOP_CENTER);
    xylineandshaperenderer1.addAnnotation(xypointerannotation1);
    xyplot.setRenderer(1, xylineandshaperenderer1);
    LegendTitle legendtitle = new LegendTitle(xylineandshaperenderer);
    LegendTitle legendtitle1 = new LegendTitle(xylineandshaperenderer1);
    BlockContainer blockcontainer = new BlockContainer(new BorderArrangement());
    blockcontainer.add(legendtitle, RectangleEdge.LEFT);
    blockcontainer.add(legendtitle1, RectangleEdge.RIGHT);
    blockcontainer.add(new EmptyBlock(2000D, 0.0D));
    CompositeTitle compositetitle = new CompositeTitle(blockcontainer);
    compositetitle.setPosition(RectangleEdge.BOTTOM);
    jfreechart.addSubtitle(compositetitle);
    return jfreechart;
}

From source file:org.jfree.chart.demo.JFreeChartDemoBase.java

/**
 * Creates and returns a sample bar chart with just one series.
 *
 * @return a sample bar chart.//from   w  ww.  j  a  va2s  .  c  o  m
 */
public JFreeChart createSingleSeriesBarChart() {

    // create a default chart based on some sample data...
    final String title = this.resources.getString("test.single.title");
    final String domain = this.resources.getString("test.single.domain");
    final String range = this.resources.getString("test.single.range");
    final String subtitle1Str = this.resources.getString("test.single.subtitle1");
    final String subtitle2Str = this.resources.getString("test.single.subtitle2");

    final CategoryDataset data = DemoDatasetFactory.createSingleSeriesCategoryDataset();

    final JFreeChart chart = ChartFactory.createBarChart(title, domain, range, data, PlotOrientation.HORIZONTAL,
            true, true, false);
    chart.addSubtitle(new TextTitle(subtitle1Str));
    chart.addSubtitle(new TextTitle(subtitle2Str));
    chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 1000, 0, Color.red));
    return chart;

}