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:com.naryx.tagfusion.cfm.tag.awt.cfCHART.java

private void setLegend(JFreeChart chart, boolean bShowLegend, Font font, Color foregroundColor,
        Color backgroundColor, cfCHARTLEGENDData legendData) throws cfmRunTimeException {
    LegendTitle legend = new LegendTitle(chart.getPlot());
    legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));

    // If a CFCHARTLEGEND tag was used then use it's attributes to configure the
    // legend//ww  w .j  av a  2s  .c  o  m
    if (legendData != null) {
        // A CFCHARTLEGEND tag is present so use its attributes to configure the
        // legend
        legend.setItemFont(getFont(legendData.getFont(), legendData.getFontBold(), legendData.getFontItalic(),
                legendData.getFontSize()));
        legend.setItemPaint(convertStringToColor(legendData.getLabelColor()));
        legend.setBackgroundPaint(convertStringToColor(legendData.getBackgroundColor()));

        String pos = legendData.getPosition();
        if (pos.equals("top"))
            legend.setPosition(RectangleEdge.TOP);
        else if (pos.equals("bottom"))
            legend.setPosition(RectangleEdge.BOTTOM);
        else if (pos.equals("left"))
            legend.setPosition(RectangleEdge.LEFT);
        else if (pos.equals("right"))
            legend.setPosition(RectangleEdge.RIGHT);

        if (!legendData.getShowBorder())
            legend.setBorder(BlockBorder.NONE);
        else
            legend.setBorder(new BlockBorder());
    } else {
        // A CFCHARTLEGEND tag is NOT present so use the attributes from the
        // CFCHART tag to configure the legend
        if (!bShowLegend)
            return;

        legend.setItemFont(font);
        legend.setItemPaint(foregroundColor);
        legend.setBackgroundPaint(backgroundColor);

        // By default CFMX 7 places the legend at the top with no border
        legend.setPosition(RectangleEdge.TOP);
        legend.setBorder(BlockBorder.NONE);
    }

    // Add the legend to the chart
    chart.addSubtitle(legend);
}

From source file:maltcms.ui.fileHandles.csv.CSV2JFCLoader.java

@Override
public void run() {
    CSV2TableLoader tl = new CSV2TableLoader(this.ph, this.is);

    DefaultTableModel dtm;//from  w w w  .  ja va 2s.  co  m
    try {
        dtm = tl.call();
        if (this.mode == CHART.XY) {
            XYSeriesCollection cd = new XYSeriesCollection();
            for (int j = 0; j < dtm.getColumnCount(); j++) {
                XYSeries xys = new XYSeries(dtm.getColumnName(j));
                for (int i = 0; i < dtm.getRowCount(); i++) {
                    Object o = dtm.getValueAt(i, j);
                    try {
                        double d = Double.parseDouble(o.toString());
                        xys.add(i, d);
                        Logger.getLogger(getClass().getName()).log(Level.INFO, "Adding {0} {1} {2}",
                                new Object[] { i, d, dtm.getColumnName(j) });
                    } catch (Exception e) {
                    }
                }
                cd.addSeries(xys);
            }
            XYLineAndShapeRenderer d = new XYLineAndShapeRenderer(true, false);
            XYPlot xyp = new XYPlot(cd, new NumberAxis("category"), new NumberAxis("value"), d);

            JFreeChart jfc = new JFreeChart(this.title, xyp);
            jtc.setChart(jfc);
            Logger.getLogger(getClass().getName()).info("creating chart done");
        } else if (this.mode == CHART.MATRIX) {
            DefaultXYZDataset cd = new DefaultXYZDataset();
            Logger.getLogger(getClass().getName()).log(Level.INFO, "Name of column 0: {0}",
                    dtm.getColumnName(0));
            if (dtm.getColumnName(0).isEmpty()) {
                Logger.getLogger(getClass().getName()).info("Removing column 0");
                dtm = removeColumn(dtm, 0);
            }
            if (dtm.getColumnName(dtm.getColumnCount() - 1).equalsIgnoreCase("filename")) {
                dtm = removeColumn(dtm, dtm.getColumnCount() - 1);
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < dtm.getRowCount(); i++) {
                for (int j = 0; j < dtm.getColumnCount(); j++) {
                    sb.append(dtm.getValueAt(i, j) + " ");
                }
                sb.append("\n");
            }
            Logger.getLogger(getClass().getName()).log(Level.INFO, "Table before sorting: {0}", sb.toString());
            //                dtm = sort(dtm);
            StringBuilder sb2 = new StringBuilder();
            for (int i = 0; i < dtm.getRowCount(); i++) {
                for (int j = 0; j < dtm.getColumnCount(); j++) {
                    sb2.append(dtm.getValueAt(i, j) + " ");
                }
                sb2.append("\n");
            }
            Logger.getLogger(getClass().getName()).log(Level.INFO, "Table after sorting: {0}", sb2.toString());
            int rows = dtm.getRowCount();
            int columns = dtm.getColumnCount();
            Logger.getLogger(getClass().getName()).log(Level.INFO, "Storing {0} * {1} elements, {2} total!",
                    new Object[] { columns, rows, rows * columns });
            double[][] data = new double[3][(columns * rows)];
            ArrayDouble.D1 dt = new ArrayDouble.D1((columns) * rows);
            double min = Double.POSITIVE_INFINITY;
            double max = Double.NEGATIVE_INFINITY;
            EvalTools.eqI(rows, columns, this);
            int k = 0;
            for (int i = 0; i < dtm.getRowCount(); i++) {
                for (int j = 0; j < dtm.getColumnCount(); j++) {

                    Object o = dtm.getValueAt(i, j);
                    try {
                        double d = Double.parseDouble(o.toString());
                        if (d < min) {
                            min = d;
                        }
                        if (d > max) {
                            max = d;
                        }
                        data[0][k] = (double) i;
                        data[1][k] = (double) j;
                        data[2][k] = d;
                        dt.set(k, d);
                        k++;
                        //System.out.println("Adding "+i+" "+d+" "+dtm.getColumnName(j));
                    } catch (Exception e) {
                    }
                }
                //cd.addSeries(xys);
            }
            cd.addSeries(this.title, data);
            XYBlockRenderer xyb = new XYBlockRenderer();
            GradientPaintScale ps = new GradientPaintScale(ImageTools.createSampleTable(256), min, max,
                    ImageTools
                            .rampToColorArray(new ColorRampReader().readColorRamp("res/colorRamps/bcgyr.csv")));

            xyb.setPaintScale(ps);
            final String[] colnames = new String[dtm.getColumnCount()];
            for (int i = 0; i < colnames.length; i++) {
                colnames[i] = dtm.getColumnName(i);
            }
            NumberAxis na1 = new SymbolAxis("category", colnames);
            na1.setVerticalTickLabels(false);
            NumberAxis na2 = new SymbolAxis("category", colnames);
            na1.setVerticalTickLabels(true);
            XYPlot xyp = new XYPlot(cd, na1, na2, xyb);
            xyb.setSeriesToolTipGenerator(0, new XYToolTipGenerator() {

                @Override
                public String generateToolTip(XYDataset xyd, int i, int i1) {
                    return "[" + colnames[xyd.getX(i, i1).intValue()] + ":"
                            + colnames[xyd.getY(i, i1).intValue()] + "] = "
                            + ((XYZDataset) xyd).getZValue(i, i1) + "";
                }
            });

            JFreeChart jfc = new JFreeChart(this.title, xyp);
            NumberAxis values = new NumberAxis("value");
            values.setAutoRange(false);
            values.setRangeWithMargins(min, max);
            PaintScaleLegend psl = new PaintScaleLegend(ps, values);
            psl.setBackgroundPaint(jfc.getBackgroundPaint());
            jfc.addSubtitle(psl);
            psl.setStripWidth(50);
            psl.setPadding(20, 20, 20, 20);
            psl.setHeight(200);
            psl.setPosition(RectangleEdge.RIGHT);
            jtc.setChart(jfc);
        }
    } catch (Exception ex) {
        Exceptions.printStackTrace(ex);
    }

    ph.finish();
}

From source file:com.manydesigns.portofino.chart.ChartStackedBarGenerator.java

public JFreeChart generate(ChartDefinition chartDefinition, Persistence persistence, Locale locale) {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    java.util.List<Object[]> result;
    String query = chartDefinition.getQuery();
    logger.info(query);//from   w w  w  . ja  v  a 2s  .  c o m
    Session session = persistence.getSession(chartDefinition.getDatabase());
    result = QueryUtils.runSql(session, query);
    for (Object[] current : result) {
        ComparableWrapper x = new ComparableWrapper((Comparable) current[0]);
        ComparableWrapper y = new ComparableWrapper((Comparable) current[1]);
        if (current.length > 3) {
            x.setLabel(current[3].toString());
        }
        if (current.length > 4) {
            y.setLabel(current[4].toString());
        }
        dataset.setValue((Number) current[2], x, y);
    }

    PlotOrientation plotOrientation = PlotOrientation.HORIZONTAL;
    if (chartDefinition.getActualOrientation() == ChartDefinition.Orientation.VERTICAL) {
        plotOrientation = PlotOrientation.VERTICAL;
    }

    JFreeChart chart = createChart(chartDefinition, dataset, plotOrientation);

    chart.setAntiAlias(antiAlias);

    // impostiamo il bordo invisibile
    // eventualmente e' il css a fornirne uno
    chart.setBorderVisible(borderVisible);

    // impostiamo il titolo
    TextTitle title = chart.getTitle();
    title.setFont(titleFont);
    title.setMargin(10.0, 0.0, 0.0, 0.0);

    // ottieni il Plot
    CategoryPlot plot = (CategoryPlot) chart.getPlot();

    CategoryItemRenderer renderer = plot.getRenderer();
    String urlExpression = chartDefinition.getUrlExpression();
    if (!StringUtils.isBlank(urlExpression)) {
        CategoryURLGenerator urlGenerator = new ChartBarUrlGenerator(chartDefinition.getUrlExpression());
        renderer.setBaseItemURLGenerator(urlGenerator);
    } else {
        renderer.setBaseItemURLGenerator(null);
    }
    renderer.setBaseOutlinePaint(Color.BLACK);

    // ///////////////
    if (renderer instanceof BarRenderer) {
        BarRenderer barRenderer = (BarRenderer) renderer;

        barRenderer.setDrawBarOutline(true);
        barRenderer.setShadowVisible(false);
        barRenderer.setBarPainter(new StandardBarPainter());

        // hongliangpan add
        // ?
        barRenderer.setSeriesItemLabelGenerator(0, new StandardCategoryItemLabelGenerator());
        // bar???
        barRenderer.setMinimumBarLength(0.02);
        // 
        barRenderer.setMaximumBarWidth(0.06);
    }
    if (renderer instanceof StackedBarRenderer3D || renderer instanceof StackedBarRenderer) {
        BarRenderer barRenderer = (BarRenderer) renderer;
        barRenderer.setDrawBarOutline(true);
        barRenderer.setShadowVisible(false);
        barRenderer.setBarPainter(new StandardBarPainter());

        // hongliangpan add
        // ? setSeriesItemLabelGenerator
        barRenderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        // bar???
        barRenderer.setMinimumBarLength(0.02);
        // 
        barRenderer.setMaximumBarWidth(0.06);
        // ?????
        ItemLabelPosition itemLabelPositionFallback = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
                TextAnchor.BASELINE_LEFT, TextAnchor.HALF_ASCENT_LEFT, -1.57D);
        // ??labelposition
        barRenderer.setPositiveItemLabelPositionFallback(itemLabelPositionFallback);
        barRenderer.setNegativeItemLabelPositionFallback(itemLabelPositionFallback);

        barRenderer.setItemLabelsVisible(true);
        barRenderer.setItemMargin(10);
    }

    // ///////////////

    // il plot ha sfondo e bordo trasparente
    // (quindi si vede il colore del chart)
    plot.setBackgroundPaint(transparentColor);
    plot.setOutlinePaint(transparentColor);

    // Modifico il toolTip
    // plot.setToolTipGenerator(new StandardPieToolTipGenerator("{0} = {1} ({2})"));

    // imposta il messaggio se non ci sono dati
    plot.setNoDataMessage(ElementsThreadLocals.getText("no.data.available"));
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.GRAY);
    plot.setAxisOffset(new RectangleInsets(0, 0, 0, 0));

    // Category axis
    CategoryAxis categoryAxis = plot.getDomainAxis();
    categoryAxis.setAxisLinePaint(Color.BLACK);
    categoryAxis.setLabelFont(axisFont);
    categoryAxis.setAxisLineVisible(true);

    // impostiamo la rotazione dell'etichetta
    if (plot.getOrientation() == PlotOrientation.VERTICAL) {
        CategoryLabelPosition pos = new CategoryLabelPosition(RectangleAnchor.TOP_LEFT,
                TextBlockAnchor.TOP_RIGHT, TextAnchor.TOP_RIGHT, -Math.PI / 4.0,
                CategoryLabelWidthType.CATEGORY, 100);
        CategoryLabelPositions positions = new CategoryLabelPositions(pos, pos, pos, pos);
        categoryAxis.setCategoryLabelPositions(positions);
        categoryAxis.setMaximumCategoryLabelWidthRatio(6.0f);
        height = 333;
    } else {
        categoryAxis.setMaximumCategoryLabelWidthRatio(0.4f);

        // recuperiamo 8 pixel a sinistra
        plot.setInsets(new RectangleInsets(4.0, 0.0, 4.0, 8.0));

        height = 74;

        // contiamo gli elementi nel dataset
        height += 23 * dataset.getColumnCount();

        height += 57;
    }

    Axis rangeAxis = plot.getRangeAxis();
    rangeAxis.setAxisLinePaint(Color.BLACK);
    rangeAxis.setLabelFont(axisFont);

    DrawingSupplier supplier = new DesaturatedDrawingSupplier(plot.getDrawingSupplier());
    plot.setDrawingSupplier(supplier);

    // impostiamo il titolo della legenda
    String legendString = chartDefinition.getLegend();
    Title subtitle = new TextTitle(legendString, legendFont, Color.BLACK, RectangleEdge.BOTTOM,
            HorizontalAlignment.CENTER, VerticalAlignment.CENTER, new RectangleInsets(0, 0, 0, 0));
    subtitle.setMargin(0, 0, 5, 0);
    chart.addSubtitle(subtitle);

    // impostiamo la legenda
    LegendTitle legend = chart.getLegend();
    legend.setBorder(0, 0, 0, 0);
    legend.setItemFont(legendItemFont);
    int legendMargin = 10;
    legend.setMargin(0.0, legendMargin, legendMargin, legendMargin);
    legend.setBackgroundPaint(transparentColor);

    // impostiamo un gradiente orizzontale
    Paint chartBgPaint = new GradientPaint(0, 0, new Color(255, 253, 240), 0, height, Color.WHITE);
    chart.setBackgroundPaint(chartBgPaint);
    return chart;
}

From source file:com.manydesigns.portofino.chart.ChartBarGenerator.java

public JFreeChart generate(ChartDefinition chartDefinition, Persistence persistence, Locale locale) {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    java.util.List<Object[]> result;
    String query = chartDefinition.getQuery();
    logger.info(query);//from  www.ja v a 2  s  .  c  o m
    Session session = persistence.getSession(chartDefinition.getDatabase());
    result = QueryUtils.runSql(session, query);
    for (Object[] current : result) {
        ComparableWrapper x = new ComparableWrapper((Comparable) current[0]);
        ComparableWrapper y = new ComparableWrapper((Comparable) current[1]);
        if (current.length > 3) {
            x.setLabel(current[3].toString());
        }
        if (current.length > 4) {
            y.setLabel(current[4].toString());
        }
        dataset.setValue((Number) current[2], x, y);
    }

    PlotOrientation plotOrientation = PlotOrientation.HORIZONTAL;
    if (chartDefinition.getActualOrientation() == ChartDefinition.Orientation.VERTICAL) {
        plotOrientation = PlotOrientation.VERTICAL;
    }

    JFreeChart chart = createChart(chartDefinition, dataset, plotOrientation);

    chart.setAntiAlias(antiAlias);

    // impostiamo il bordo invisibile
    // eventualmente e' il css a fornirne uno
    chart.setBorderVisible(borderVisible);

    // impostiamo il titolo
    TextTitle title = chart.getTitle();
    title.setFont(titleFont);
    title.setMargin(10.0, 0.0, 0.0, 0.0);

    // ottieni il Plot
    CategoryPlot plot = (CategoryPlot) chart.getPlot();

    CategoryItemRenderer renderer = plot.getRenderer();
    String urlExpression = chartDefinition.getUrlExpression();
    if (!StringUtils.isBlank(urlExpression)) {
        CategoryURLGenerator urlGenerator = new ChartBarUrlGenerator(chartDefinition.getUrlExpression());
        renderer.setBaseItemURLGenerator(urlGenerator);
    } else {
        renderer.setBaseItemURLGenerator(null);
    }
    renderer.setBaseOutlinePaint(Color.BLACK);

    // ///////////////
    if (renderer instanceof BarRenderer || renderer instanceof BarRenderer3D) {
        BarRenderer barRenderer = (BarRenderer) renderer;

        barRenderer.setDrawBarOutline(true);
        barRenderer.setShadowVisible(false);
        barRenderer.setBarPainter(new StandardBarPainter());

        // hongliangpan add
        barRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        barRenderer.setBaseItemLabelsVisible(true);
        // ? setSeriesItemLabelGenerator
        barRenderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        // bar???
        barRenderer.setMinimumBarLength(0.02);
        // 
        barRenderer.setMaximumBarWidth(0.05);
        // ?????
        // ??90,??/3.14
        ItemLabelPosition itemLabelPositionFallback = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
                TextAnchor.BASELINE_LEFT, TextAnchor.HALF_ASCENT_LEFT, -1.57D);
        // ??labelposition
        // barRenderer.setPositiveItemLabelPositionFallback(itemLabelPositionFallback);
        // barRenderer.setNegativeItemLabelPositionFallback(itemLabelPositionFallback);

        barRenderer.setItemLabelsVisible(true);

        // ?
        barRenderer.setBaseOutlinePaint(Color.BLACK);
        // ???
        barRenderer.setDrawBarOutline(true);

        // ???
        barRenderer.setItemMargin(0.0);

        // ?
        barRenderer.setIncludeBaseInRange(true);
        barRenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        barRenderer.setBaseItemLabelsVisible(true);
        // ?
        plot.setForegroundAlpha(1.0f);
    }

    // ///////////////

    // il plot ha sfondo e bordo trasparente
    // (quindi si vede il colore del chart)
    plot.setBackgroundPaint(transparentColor);
    plot.setOutlinePaint(transparentColor);

    // Modifico il toolTip
    // plot.setToolTipGenerator(new StandardPieToolTipGenerator("{0} = {1} ({2})"));

    // imposta il messaggio se non ci sono dati
    plot.setNoDataMessage(ElementsThreadLocals.getText("no.data.available"));
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.GRAY);
    plot.setAxisOffset(new RectangleInsets(0, 0, 0, 0));

    // Category axis
    CategoryAxis categoryAxis = plot.getDomainAxis();
    categoryAxis.setAxisLinePaint(Color.BLACK);
    categoryAxis.setLabelFont(axisFont);
    categoryAxis.setAxisLineVisible(true);

    // impostiamo la rotazione dell'etichetta
    if (plot.getOrientation() == PlotOrientation.VERTICAL) {
        CategoryLabelPosition pos = new CategoryLabelPosition(RectangleAnchor.TOP_LEFT,
                TextBlockAnchor.TOP_RIGHT, TextAnchor.TOP_RIGHT, -Math.PI / 4.0,
                CategoryLabelWidthType.CATEGORY, 100);
        CategoryLabelPositions positions = new CategoryLabelPositions(pos, pos, pos, pos);
        categoryAxis.setCategoryLabelPositions(positions);
        categoryAxis.setMaximumCategoryLabelWidthRatio(6.0f);
        height = 333;
    } else {
        categoryAxis.setMaximumCategoryLabelWidthRatio(0.4f);

        // recuperiamo 8 pixel a sinistra
        plot.setInsets(new RectangleInsets(4.0, 0.0, 4.0, 8.0));

        height = 74;

        // contiamo gli elementi nel dataset
        height += 23 * dataset.getColumnCount();

        height += 57;
    }

    Axis rangeAxis = plot.getRangeAxis();
    rangeAxis.setAxisLinePaint(Color.BLACK);
    rangeAxis.setLabelFont(axisFont);

    DrawingSupplier supplier = new DesaturatedDrawingSupplier(plot.getDrawingSupplier());
    plot.setDrawingSupplier(supplier);

    // impostiamo il titolo della legenda
    String legendString = chartDefinition.getLegend();
    Title subtitle = new TextTitle(legendString, legendFont, Color.BLACK, RectangleEdge.BOTTOM,
            HorizontalAlignment.CENTER, VerticalAlignment.CENTER, new RectangleInsets(0, 0, 0, 0));
    subtitle.setMargin(0, 0, 5, 0);
    chart.addSubtitle(subtitle);

    // impostiamo la legenda
    LegendTitle legend = chart.getLegend();
    legend.setBorder(0, 0, 0, 0);
    legend.setItemFont(legendItemFont);
    int legendMargin = 10;
    legend.setMargin(0.0, legendMargin, legendMargin, legendMargin);
    legend.setBackgroundPaint(transparentColor);

    // impostiamo un gradiente orizzontale
    Paint chartBgPaint = new GradientPaint(0, 0, new Color(255, 253, 240), 0, height, Color.WHITE);
    chart.setBackgroundPaint(chartBgPaint);
    return chart;
}

From source file:net.sf.fspdfs.chartthemes.spring.GenericChartTheme.java

protected void setChartSubtitles(JFreeChart jfreeChart, Integer baseFontSize) throws JRException {
    Boolean subtitleVisibility = (Boolean) getDefaultValue(defaultChartPropertiesMap,
            ChartThemesConstants.SUBTITLE_VISIBLE);

    if (subtitleVisibility != null && subtitleVisibility.booleanValue()) {
        String subtitleText = (String) evaluateExpression(getChart().getSubtitleExpression());
        if (subtitleText != null) {
            TextTitle subtitle = new TextTitle(subtitleText);

            Font themeSubtitleFont = getFont(
                    (JRFont) getDefaultValue(defaultChartPropertiesMap, ChartThemesConstants.SUBTITLE_FONT),
                    getChart().getSubtitleFont(), baseFontSize);
            subtitle.setFont(themeSubtitleFont);

            HorizontalAlignment defaultSubtitleHAlignment = (HorizontalAlignment) getDefaultValue(
                    defaultChartPropertiesMap, ChartThemesConstants.SUBTITLE_HORIZONTAL_ALIGNMENT);
            if (defaultSubtitleHAlignment != null)
                subtitle.setHorizontalAlignment(defaultSubtitleHAlignment);

            VerticalAlignment defaultSubtitleVAlignment = (VerticalAlignment) getDefaultValue(
                    defaultChartPropertiesMap, ChartThemesConstants.SUBTITLE_VERTICAL_ALIGNMENT);
            if (defaultSubtitleVAlignment != null)
                subtitle.setVerticalAlignment(defaultSubtitleVAlignment);

            RectangleInsets defaultSubtitlePadding = (RectangleInsets) getDefaultValue(
                    defaultChartPropertiesMap, ChartThemesConstants.SUBTITLE_PADDING);
            RectangleInsets subtitlePadding = subtitle.getPadding() != null ? subtitle.getPadding()
                    : defaultSubtitlePadding;
            if (subtitlePadding != null)
                subtitle.setPadding(subtitlePadding);

            Color subtitleForecolor = getChart().getOwnSubtitleColor() != null
                    ? getChart().getOwnSubtitleColor()
                    : (getDefaultValue(defaultChartPropertiesMap,
                            ChartThemesConstants.SUBTITLE_FORECOLOR) != null
                                    ? (Color) getDefaultValue(defaultChartPropertiesMap,
                                            ChartThemesConstants.SUBTITLE_FORECOLOR)
                                    : getChart().getSubtitleColor());
            if (subtitleForecolor != null)
                subtitle.setPaint(subtitleForecolor);

            Color subtitleBackcolor = getDefaultValue(defaultChartPropertiesMap,
                    ChartThemesConstants.SUBTITLE_BACKCOLOR) != null
                            ? (Color) getDefaultValue(defaultChartPropertiesMap,
                                    ChartThemesConstants.SUBTITLE_BACKCOLOR)
                            : null;//  w  w  w  . j av a  2  s. c o  m
            if (subtitleBackcolor != null)
                subtitle.setBackgroundPaint(subtitleBackcolor);

            RectangleEdge defaultSubtitlePosition = (RectangleEdge) getDefaultValue(defaultChartPropertiesMap,
                    ChartThemesConstants.SUBTITLE_POSITION);
            //Subtitle has not its own position set, and by default this will be set the same as title position
            RectangleEdge subtitleEdge = null;
            if (defaultSubtitlePosition == null) {
                subtitleEdge = jfreeChart.getTitle().getPosition();
            } else {
                subtitleEdge = defaultSubtitlePosition;
            }
            if (subtitleEdge != null)
                subtitle.setPosition(subtitleEdge);

            jfreeChart.addSubtitle(subtitle);
        }
    }
}

From source file:net.sf.jasperreports.chartthemes.spring.GenericChartTheme.java

protected void setChartSubtitles(JFreeChart jfreeChart, Integer baseFontSize) throws JRException {
    Boolean subtitleVisibility = (Boolean) getDefaultValue(defaultChartPropertiesMap,
            ChartThemesConstants.SUBTITLE_VISIBLE);

    if (subtitleVisibility != null && subtitleVisibility) {
        String subtitleText = evaluateTextExpression(getChart().getSubtitleExpression());
        if (subtitleText != null) {
            TextTitle subtitle = new TextTitle(subtitleText);

            Font themeSubtitleFont = getFont(
                    (JRFont) getDefaultValue(defaultChartPropertiesMap, ChartThemesConstants.SUBTITLE_FONT),
                    getChart().getSubtitleFont(), baseFontSize);
            subtitle.setFont(themeSubtitleFont);

            HorizontalAlignment defaultSubtitleHAlignment = (HorizontalAlignment) getDefaultValue(
                    defaultChartPropertiesMap, ChartThemesConstants.SUBTITLE_HORIZONTAL_ALIGNMENT);
            if (defaultSubtitleHAlignment != null)
                subtitle.setHorizontalAlignment(defaultSubtitleHAlignment);

            VerticalAlignment defaultSubtitleVAlignment = (VerticalAlignment) getDefaultValue(
                    defaultChartPropertiesMap, ChartThemesConstants.SUBTITLE_VERTICAL_ALIGNMENT);
            if (defaultSubtitleVAlignment != null)
                subtitle.setVerticalAlignment(defaultSubtitleVAlignment);

            RectangleInsets defaultSubtitlePadding = (RectangleInsets) getDefaultValue(
                    defaultChartPropertiesMap, ChartThemesConstants.SUBTITLE_PADDING);
            RectangleInsets subtitlePadding = subtitle.getPadding() != null ? subtitle.getPadding()
                    : defaultSubtitlePadding;
            if (subtitlePadding != null)
                subtitle.setPadding(subtitlePadding);

            Color subtitleForecolor = getChart().getOwnSubtitleColor() != null
                    ? getChart().getOwnSubtitleColor()
                    : (getDefaultValue(defaultChartPropertiesMap,
                            ChartThemesConstants.SUBTITLE_FORECOLOR) != null
                                    ? (Color) getDefaultValue(defaultChartPropertiesMap,
                                            ChartThemesConstants.SUBTITLE_FORECOLOR)
                                    : getChart().getSubtitleColor());
            if (subtitleForecolor != null)
                subtitle.setPaint(subtitleForecolor);

            Color subtitleBackcolor = getDefaultValue(defaultChartPropertiesMap,
                    ChartThemesConstants.SUBTITLE_BACKCOLOR) != null
                            ? (Color) getDefaultValue(defaultChartPropertiesMap,
                                    ChartThemesConstants.SUBTITLE_BACKCOLOR)
                            : null;/*from   w  ww . j a  v  a  2s.  c om*/
            if (subtitleBackcolor != null)
                subtitle.setBackgroundPaint(subtitleBackcolor);

            RectangleEdge defaultSubtitlePosition = (RectangleEdge) getDefaultValue(defaultChartPropertiesMap,
                    ChartThemesConstants.SUBTITLE_POSITION);
            //Subtitle has not its own position set, and by default this will be set the same as title position
            RectangleEdge subtitleEdge = null;
            if (defaultSubtitlePosition == null) {
                subtitleEdge = jfreeChart.getTitle().getPosition();
            } else {
                subtitleEdge = defaultSubtitlePosition;
            }
            if (subtitleEdge != null)
                subtitle.setPosition(subtitleEdge);

            jfreeChart.addSubtitle(subtitle);
        }
    }
}

From source file:org.jfree.eastwood.ChartEngine.java

/**
 * Creates and returns a new <code>JFreeChart</code> instance that
 * reflects the specified parameters (which should be equivalent to
 * a parameter map returned by HttpServletRequest.getParameterMap() for
 * a valid URI for the Google Chart API.
 *
 * @param params  the parameters (<code>null</code> not permitted).
 * @param font    the font to use to draw titles, labels and legends.
 *
 * @return A chart corresponding to the specification in the supplied
 *         parameters.//w  w  w. j  a va  2  s  . c o  m
 */
public static JFreeChart buildChart(Map params, Font font) {
    if (params == null) {
        throw new IllegalArgumentException("Null 'params' argument.");
    }

    JFreeChart chart = null;

    // *** CHART TYPE **
    String[] chartType = (String[]) params.get("cht");
    int dataType = -1; // 0 = PieDataset; 1 = XYDataset; 2 = special

    // pie charts: 'p' and 'p3'
    if (chartType[0].equals("p")) {
        chart = createPieChart();
        dataType = 0;
    } else if (chartType[0].equals("p3")) {
        chart = createPieChart3D();
        dataType = 0;
    }
    // line chart: 'lc'
    else if (chartType[0].equals("lc")) {
        chart = createLineChart();
        dataType = 1;
    }
    // sparkline: 'ls'
    else if (chartType[0].equals("ls")) {
        chart = createSparklineChart();
        dataType = 1;
    }
    // xy chart: 'lxy'
    else if (chartType[0].equals("lxy")) {
        chart = createLineChart();
        dataType = 3;
    }
    // bar charts: 'bhs', 'bhg', 'bhs' and 'bhg'
    else if (chartType[0].equals("bhs")) {
        chart = createStackedBarChart(PlotOrientation.HORIZONTAL);
        dataType = 2;
    } else if (chartType[0].equals("bhg")) {
        chart = createBarChart(PlotOrientation.HORIZONTAL);
        dataType = 2;
    } else if (chartType[0].equals("bvs")) {
        chart = createStackedBarChart(PlotOrientation.VERTICAL);
        dataType = 2;
    } else if (chartType[0].equals("bvg")) {
        chart = createBarChart(PlotOrientation.VERTICAL);
        dataType = 2;
    } else if (chartType[0].equals("bhs3")) {
        chart = createStackedBarChart3D(PlotOrientation.HORIZONTAL);
        dataType = 2;
    } else if (chartType[0].equals("bhg3")) {
        chart = createBarChart3D(PlotOrientation.HORIZONTAL);
        dataType = 2;
    } else if (chartType[0].equals("bvs3")) {
        chart = createStackedBarChart3D(PlotOrientation.VERTICAL);
        dataType = 2;
    } else if (chartType[0].equals("bvg3")) {
        chart = createBarChart3D(PlotOrientation.VERTICAL);
        dataType = 2;
    }
    // scatter chart: 's'
    else if (chartType[0].equals("s")) {
        chart = createScatterChart();
        dataType = 4;
    } else if (chartType[0].equals("v")) {
        throw new RuntimeException("Venn diagrams not implemented.");
        // TODO: fix this.
    } else {
        throw new RuntimeException("Unknown chart type: " + chartType[0]);
    }

    chart.getPlot().setOutlineVisible(false);

    // *** CHART AXES ***
    List axes = new java.util.ArrayList();
    String[] axisStr = (String[]) params.get("chxt");
    if (axisStr != null) {
        if (chart.getPlot() instanceof XYPlot) {
            XYPlot plot = (XYPlot) chart.getPlot();
            processAxisStr(plot, axisStr[0], axes);
        } else if (chart.getPlot() instanceof CategoryPlot) {
            CategoryPlot plot = (CategoryPlot) chart.getPlot();
            if (plot.getOrientation() == PlotOrientation.VERTICAL) {
                processAxisStrV(plot, axisStr[0], axes);
            } else {
                processAxisStrH(plot, axisStr[0], axes);
            }
        }
    }

    // *** AXIS RANGES ***
    String[] axisRangeStr = (String[]) params.get("chxr");
    if (axisRangeStr != null) {
        String[] ranges = breakString(axisRangeStr[0], '|');
        for (int i = 0; i < ranges.length; i++) {
            int comma1 = ranges[i].indexOf(',');
            int comma2 = ranges[i].indexOf(',', comma1 + 1);
            int axisIndex = Integer.parseInt(ranges[i].substring(0, comma1));
            float lowerBound = Float.parseFloat(ranges[i].substring(comma1 + 1, comma2));
            float upperBound = Float.parseFloat(ranges[i].substring(comma2 + 1));
            Axis axis = (Axis) axes.get(axisIndex);
            if (axis instanceof GValueAxis) {
                GValueAxis gaxis = (GValueAxis) axis;
                gaxis.setLabelAxisStart(lowerBound);
                gaxis.setLabelAxisEnd(upperBound);
            }
        }
    }

    // *** AXIS LABELS ***
    String[] axisLabelStr = (String[]) params.get("chxl");
    if (axisLabelStr != null) {
        Pattern p = Pattern.compile("\\d+:\\|");
        Matcher m = p.matcher(axisLabelStr[0]);
        if (m.find()) {
            int keyStart = m.start();
            int labelStart = m.end();
            while (m.find(labelStart)) {
                String keyStr = axisLabelStr[0].substring(keyStart, labelStart - 2);
                int axisIndex = Integer.parseInt(keyStr);
                keyStart = m.start();
                String labelStr = axisLabelStr[0].substring(labelStart, keyStart - 1);
                String[] labels = breakString(labelStr, '|');
                GLabelledAxis axis = (GLabelledAxis) axes.get(axisIndex);
                axis.setTickLabels(Arrays.asList(labels));
                labelStart = m.end();
            }
            // process the final item
            String keyStr = axisLabelStr[0].substring(keyStart, labelStart - 2);
            String labelStr = axisLabelStr[0].substring(labelStart);
            int axisIndex = Integer.parseInt(keyStr);
            if (labelStr.endsWith("|")) {
                labelStr = labelStr.substring(0, labelStr.length() - 1);
            }
            String[] labels = breakString(labelStr, '|');
            GLabelledAxis axis = (GLabelledAxis) axes.get(axisIndex);
            axis.setTickLabels(Arrays.asList(labels));

        } else {
            throw new RuntimeException("No matching pattern!");
        }

    }

    // ** EXPLICIT AXIS LABEL POSITIONS
    String[] axisPositionStr = (String[]) params.get("chxp");
    if (axisPositionStr != null) {
        String[] positions = breakString(axisPositionStr[0], '|');
        for (int i = 0; i < positions.length; i++) {
            int c1 = positions[i].indexOf(',');
            int axisIndex = Integer.parseInt(positions[i].substring(0, c1));
            String remainingStr = positions[i].substring(c1 + 1);
            String[] valueStr = breakString(remainingStr, ',');
            List tickValues = new java.util.ArrayList(valueStr.length);
            Axis axis = (Axis) axes.get(axisIndex);
            if (axis instanceof GValueAxis) {
                GValueAxis gaxis = (GValueAxis) axes.get(axisIndex);
                for (int j = 0; j < valueStr.length; j++) {
                    float pos = Float.parseFloat(valueStr[j]);
                    tickValues.add(new Float(pos));
                }
                gaxis.setTickLabelPositions(tickValues);
            }
            // FIXME: what about a CategoryAxis?
        }
    }

    // *** CHART TITLE ***
    String[] titleStr = (String[]) params.get("chtt");
    if (titleStr != null) {
        // process the title
        String[] s = breakString(titleStr[0], '|');
        for (int i = 0; i < s.length; i++) {
            TextTitle t = new TextTitle(s[i].replace('+', ' '));
            t.setPaint(Color.darkGray);
            // Google seems to use 14pt fonts for titles and 12pt fonts for
            // all other text. Make sure this relationship remains.
            t.setFont(font.deriveFont(font.getSize2D() * 14f / 12f));
            chart.addSubtitle(t);
        }
        // and the font and colour
        String[] fontStr = (String[]) params.get("chts");
        if (fontStr != null) {
            int c1 = fontStr[0].indexOf(',');
            String colorStr = null;
            String fontSizeStr = null;
            if (c1 != -1) {
                colorStr = fontStr[0].substring(0, c1);
                fontSizeStr = fontStr[0].substring(c1 + 1);
            } else {
                colorStr = fontStr[0];
            }
            Color color = parseColor(colorStr);
            int size = 12;
            if (fontSizeStr != null) {
                size = Integer.parseInt(fontSizeStr);
            }
            for (int i = 0; i < chart.getSubtitleCount(); i++) {
                Title t = chart.getSubtitle(i);
                if (t instanceof TextTitle) {
                    TextTitle tt = (TextTitle) t;
                    tt.setPaint(color);
                    tt.setFont(font.deriveFont((float) size));
                }
            }
        }
    }

    // *** CHART DATA ***
    String[] dataStr = (String[]) params.get("chd");
    String scalingStr = null;
    if (dataStr.length > 0 && dataStr[0].startsWith("t:")) {
        // Only look at chds when text encoding is used
        String[] chds = (String[]) params.get("chds");
        if (chds != null && chds.length > 0) {
            scalingStr = chds[0];
        }
    }

    // we'll also process an optional second dataset that is provided as
    // an Eastwood extension...this isn't part of the Google Chart API
    String[] d2Str = (String[]) params.get("ewd2");

    // 'p' and 'p3' - create PieDataset
    if (dataType == 0) {
        PieDataset dataset = DataUtilities.parsePieDataset(dataStr[0], scalingStr);
        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setDataset(dataset);

        // ignore d2Str as there is currently no need for a second pie
        // dataset.
    }

    // 'lc' - create XYDataset
    else if (dataType == 1) {
        XYPlot plot = (XYPlot) chart.getPlot();
        XYDataset dataset = DataUtilities.parseXYDataset(dataStr[0], scalingStr);
        plot.setDataset(dataset);

        if (d2Str != null) { // an Eastwood extension
            XYDataset d2 = DataUtilities.parseXYDataset(d2Str[0], scalingStr);
            plot.setDataset(1, d2);
        }
    }

    // 'bhs', 'bhg', 'bvs', 'bvg'
    else if (dataType == 2) {
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        CategoryDataset dataset = DataUtilities.parseCategoryDataset(dataStr[0], scalingStr);
        plot.setDataset(dataset);

        if (d2Str != null) { // an Eastwood extension
            CategoryDataset d2 = DataUtilities.parseCategoryDataset(d2Str[0], scalingStr);
            plot.setDataset(1, d2);
        }
    }

    // 'lxy'
    else if (dataType == 3) {
        XYPlot plot = (XYPlot) chart.getPlot();
        XYDataset dataset = DataUtilities.parseXYDataset2(dataStr[0], scalingStr);
        plot.setDataset(dataset);

        if (d2Str != null) { // an Eastwood extension
            XYDataset d2 = DataUtilities.parseXYDataset2(d2Str[0], scalingStr);
            plot.setDataset(1, d2);
        }
    } else if (dataType == 4) {
        XYPlot plot = (XYPlot) chart.getPlot();
        XYSeriesCollection dataset = DataUtilities.parseScatterDataset(dataStr[0], scalingStr);
        if (dataset.getSeriesCount() > 1) {
            dataset.removeSeries(1);
        }
        plot.setDataset(dataset);
        if (d2Str != null) { // an Eastwood extension
            XYDataset d2 = DataUtilities.parseXYDataset2(d2Str[0], scalingStr);
            plot.setDataset(1, d2);
        }
    }

    if (chart.getPlot() instanceof XYPlot) {
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.getDomainAxis().setLabelFont(font);
        plot.getDomainAxis().setTickLabelFont(font);
        plot.getRangeAxis().setLabelFont(font);
        plot.getRangeAxis().setTickLabelFont(font);
    } else if (chart.getPlot() instanceof CategoryPlot) {
        CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.getDomainAxis().setLabelFont(font);
        plot.getDomainAxis().setTickLabelFont(font);
        plot.getRangeAxis().setLabelFont(font);
        plot.getRangeAxis().setTickLabelFont(font);
    }

    // *** CHART COLOURS ***
    String[] colorStr = (String[]) params.get("chco");
    if (colorStr != null) {
        Color[] colors = parseColors(colorStr[0]);
        if (dataType == 0) {
            PiePlot plot = (PiePlot) chart.getPlot();
            applyColorsToPiePlot(plot, colors);
        } else {
            AbstractRenderer renderer = null;
            if (chart.getPlot() instanceof CategoryPlot) {
                CategoryPlot plot = (CategoryPlot) chart.getPlot();
                renderer = (AbstractRenderer) plot.getRenderer();
                renderer.setBasePaint(colors[0]);
            } else if (chart.getPlot() instanceof XYPlot) {
                XYPlot plot = (XYPlot) chart.getPlot();
                renderer = (AbstractRenderer) plot.getRenderer();
                renderer.setBasePaint(colors[colors.length - 1]);
            }
            for (int i = 0; i < colors.length; i++) {
                renderer.setSeriesPaint(i, colors[i]);
            }
        }
    } else {
        Plot plot = chart.getPlot();
        if (plot instanceof PiePlot) {
            applyColorsToPiePlot((PiePlot) chart.getPlot(), new Color[] { new Color(255, 153, 0) });
        }
    }

    // *** CHART LINE STYLES ***
    String[] lineStr = (String[]) params.get("chls");
    if (lineStr != null && chart.getPlot() instanceof XYPlot) {
        Stroke[] strokes = parseLineStyles(lineStr[0]);
        XYPlot plot = (XYPlot) chart.getPlot();
        XYItemRenderer renderer = plot.getRenderer();
        for (int i = 0; i < strokes.length; i++) {
            renderer.setSeriesStroke(i, strokes[i]);
        }
        renderer.setBaseStroke(strokes[strokes.length - 1]);
    }

    // *** CHART GRID LINES
    if (dataType != 0) {
        String[] gridStr = (String[]) params.get("chg");
        if (gridStr != null) {
            processGridLinesSpec(gridStr[0], chart);
        }
    }

    // *** CHART LABELS
    if (dataType == 0) { // pie chart
        String[] labelStr = (String[]) params.get("chl");
        if (labelStr != null) {
            String[] s = breakString(labelStr[0], '|');
            List labels = Arrays.asList(s);
            PiePlot plot = (PiePlot) chart.getPlot();
            if (labels.size() > 0) {
                plot.setLabelGenerator(new GPieSectionLabelGenerator(labels));
                plot.setLabelFont(font);
                plot.setLabelPaint(Color.darkGray);
            }
        }
    }

    String[] legendStr = (String[]) params.get("chdl");
    if (legendStr != null) {
        // process the title
        String[] s = breakString(legendStr[0], '|');
        List labels = Arrays.asList(s);
        if (labels.size() > 0) {
            Plot p = chart.getPlot();
            if (p instanceof CategoryPlot) {
                CategoryPlot plot = (CategoryPlot) chart.getPlot();
                BarRenderer renderer = (BarRenderer) plot.getRenderer();
                renderer.setLegendItemLabelGenerator(new GSeriesLabelGenerator(labels));
                renderer.setBaseSeriesVisibleInLegend(false);
                for (int i = 0; i < labels.size(); i++) {
                    renderer.setSeriesVisibleInLegend(i, Boolean.TRUE);
                }
            } else if (p instanceof XYPlot) {
                XYPlot plot = (XYPlot) chart.getPlot();
                XYItemRenderer renderer = plot.getRenderer();
                renderer.setLegendItemLabelGenerator(new GSeriesLabelGenerator(labels));
                renderer.setBaseSeriesVisibleInLegend(false);
                for (int i = 0; i < labels.size(); i++) {
                    renderer.setSeriesVisibleInLegend(i, Boolean.TRUE);
                }
            } else if (p instanceof PiePlot) {
                PiePlot plot = (PiePlot) chart.getPlot();
                plot.setLegendLabelGenerator(new GPieSectionLabelGenerator(labels));
            }

            LegendTitle legend = new LegendTitle(chart.getPlot());
            RectangleEdge pos = RectangleEdge.RIGHT;
            String[] chdlp = (String[]) params.get("chdlp");
            if (chdlp != null) {
                if ("b".equals(chdlp[0])) {
                    pos = RectangleEdge.BOTTOM;
                } else if ("t".equals(chdlp[0])) {
                    pos = RectangleEdge.TOP;
                } else if ("l".equals(chdlp[0])) {
                    pos = RectangleEdge.LEFT;
                }
            }
            legend.setPosition(pos);
            legend.setItemFont(font);
            legend.setItemPaint(Color.darkGray);
            chart.addSubtitle(legend);
        }
    }

    // *** CHART MARKERS ***
    String[] markerStr = (String[]) params.get("chm");
    if (markerStr != null) {
        String[] markers = breakString(markerStr[0], '|');
        for (int i = 0; i < markers.length; i++) {
            addMarker(markers[i], chart);
        }
    }

    // *** CHART FILL ***/
    String[] fillStr = (String[]) params.get("chf");
    if (fillStr != null) {
        // process the 1 or 2 fill specs
        int i = fillStr[0].indexOf('|');
        if (i == -1) {
            processFillSpec(fillStr[0], chart);
        } else {
            String fs1 = fillStr[0].substring(0, i);
            String fs2 = fillStr[0].substring(i + 1);
            processFillSpec(fs1, chart);
            processFillSpec(fs2, chart);
        }
    }

    // process the 'ewtr' tag, if present
    processEWTR(params, chart);

    return chart;

}

From source file:com.tonbeller.jpivot.chart.ChartComponent.java

/**
 * Entry point for producing charts, called by wcf render tag.
 * Produces a jfreechart dataset from olap model, then creates a chart and
 * writes it to the servlet container temp directory.
 * Returns a DOM document for Renderer to transform into html.
 * Requires that jfreechart servlet is installed in this application context.
 */// w  w w  .  ja v a2s .  c  o m
public Document render(RequestContext context) throws Exception {
    // check if we need to produce a new chart
    if (dirty) {
        // clear old listeners
        dispatcher.clear();
        this.result = olapModel.getResult();
        this.cellIterator = result.getCells().iterator();
        this.dimCount = result.getAxes().length;
        DefaultCategoryDataset dataset = null;
        switch (dimCount) {
        case 1:
            logger.info("1-dim data");
            dataset = build1dimDataset();
            break;
        case 2:
            logger.info("2-dim data");
            dataset = build2dimDataset();
            break;
        default:
            logger.error("less than 1 or more than 2 dimensions");
            throw new IllegalArgumentException("ChartRenderer requires a 1 or 2 dimensional result");
        }
        // re-set dirty flag
        dirty = false;

        // create font
        titleFont = new java.awt.Font(fontName, fontStyle, fontSize);

        CategoryURLGenerator urlGenerator = new jpivotCategoryURLGenerator(webControllerURL);

        // Create the chart object
        JFreeChart chart = null;
        switch (chartType) {
        case 1:
            chart = ChartFactory.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset,
                    PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
            break;
        case 2:
            chart = ChartFactory.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset,
                    PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
            break;
        case 3:
            chart = ChartFactory.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset,
                    PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
            break;
        case 4:
            chart = ChartFactory.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset,
                    PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
            break;
        case 5:
            chart = ChartFactory.createStackedBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                    dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                    urlGenerator);
            break;
        case 6:
            chart = ChartFactory.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                    dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                    urlGenerator);
            break;
        case 7:
            chart = ChartFactory.createStackedBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                    dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                    urlGenerator);
            break;
        case 8:
            chart = ChartFactory.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                    dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                    urlGenerator);
            break;
        case 9:
            chart = ChartFactory.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset,
                    PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
            break;
        case 10:
            chart = ChartFactory.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset,
                    PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
            break;
        case 11:
            chart = ChartFactory.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset,
                    PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
            break;
        case 12:
            chart = ChartFactory.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel, dataset,
                    PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
            break;

        case 13:
            chart = ChartFactory.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                    dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                    urlGenerator);
            break;
        case 14:
            chart = ChartFactory.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                    dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                    urlGenerator);
            break;

        case 15:
            chart = ChartFactory.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                    showLegend, showTooltips, drillThroughEnabled,
                    new jpivotPieURLGenerator(TableOrder.BY_COLUMN, dataset, webControllerURL));
            break;
        case 16:
            chart = ChartFactory.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW, showLegend,
                    showTooltips, drillThroughEnabled,
                    new jpivotPieURLGenerator(TableOrder.BY_ROW, dataset, webControllerURL));
            break;
        case 17:
            chart = ChartFactory.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                    showLegend, showTooltips, drillThroughEnabled,
                    new jpivotPieURLGenerator(TableOrder.BY_COLUMN, dataset, webControllerURL));

            break;
        case 18:
            chart = ChartFactory.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW, showLegend,
                    showTooltips, drillThroughEnabled,
                    new jpivotPieURLGenerator(TableOrder.BY_ROW, dataset, webControllerURL));

            break;

        default:
            throw new Exception("An unknown Chart Type was requested");
        }
        try {
            chart.setBackgroundPaint(new java.awt.Color(bgColorR, bgColorG, bgColorB));

            java.awt.Font slicerFont = new java.awt.Font(slicerFontName, slicerFontStyle, slicerFontSize);
            java.awt.Font axisFont = new java.awt.Font(axisFontName, axisFontStyle, axisFontSize);
            java.awt.Font axisTickFont = new java.awt.Font(axisTickFontName, axisTickFontStyle,
                    axisTickFontSize);
            java.awt.Font legendFont = new java.awt.Font(legendFontName, legendFontStyle, legendFontSize);
            Plot plot = chart.getPlot();

            if (plot instanceof CategoryPlot) {
                CategoryPlot catPlot = (CategoryPlot) plot;
                catPlot.getDomainAxis().setLabelFont(axisFont);
                catPlot.getRangeAxis().setLabelFont(axisFont);
                catPlot.getDomainAxis().setTickLabelFont(axisTickFont);
                catPlot.getRangeAxis().setTickLabelFont(axisTickFont);
                catPlot.getDomainAxis().setMaximumCategoryLabelWidthRatio(100.0f);
                double angle = -2.0 * Math.PI / 360.0 * (double) tickLabelRotate;
                CategoryLabelPositions oldp = catPlot.getDomainAxis().getCategoryLabelPositions();
                CategoryLabelPositions newp = new CategoryLabelPositions(
                        oldp.getLabelPosition(RectangleEdge.TOP),
                        new CategoryLabelPosition(RectangleAnchor.TOP, TextBlockAnchor.TOP_RIGHT,
                                TextAnchor.TOP_RIGHT, angle, CategoryLabelWidthType.RANGE, 0.0f),
                        oldp.getLabelPosition(RectangleEdge.LEFT), oldp.getLabelPosition(RectangleEdge.RIGHT));
                catPlot.getDomainAxis().setCategoryLabelPositions(newp);
            } else if (plot instanceof PiePlot3D) {
                PiePlot3D piePlot = (PiePlot3D) plot;
                //piePlot.setSectionLabelFont(axisFont);
                piePlot.setLabelFont(axisFont);
                //piePlot.setSeriesLabelFont(axisTickFont);
                //piePlot.setSectionLabelType(piePlot.NO_LABELS);
                piePlot.setDirection(org.jfree.util.Rotation.CLOCKWISE);
                piePlot.setForegroundAlpha(0.5f);
                piePlot.setNoDataMessage("No data to display");
            } else if (plot instanceof PiePlot) {
                PiePlot piePlot = (PiePlot) plot;
                //piePlot.setSectionLabelFont(axisFont);
                //piePlot.setSeriesLabelFont(axisTickFont);
                piePlot.setLabelFont(axisFont);
                //piePlot.setSectionLabelType(piePlot.NO_LABELS);

            }
            LegendTitle legend = (LegendTitle) chart.getLegend();
            if (legend != null) {
                legend.setItemFont(legendFont);
                /*
                     RectangleAnchor legendRectAnchor=RectangleAnchor.BOTTOM;
                        
                switch (legendPosition){
                     case 0:
                        legendRectAnchor = RectangleAnchor.LEFT;
                        break;
                    case 1:
                       legendRectAnchor = RectangleAnchor.TOP;
                        break;
                    case 2:
                       legendRectAnchor = RectangleAnchor.RIGHT;
                        break;
                    case 3:
                       legendRectAnchor = RectangleAnchor.BOTTOM;
                        break;
                }
                legend.setLegendItemGraphicAnchor(legendRectAnchor);
                */
                RectangleEdge legendRectEdge = RectangleEdge.BOTTOM;
                switch (legendPosition) {
                case 0:
                    legendRectEdge = RectangleEdge.LEFT;
                    break;
                case 1:
                    legendRectEdge = RectangleEdge.TOP;
                    break;
                case 2:
                    legendRectEdge = RectangleEdge.RIGHT;
                    break;
                case 3:
                    legendRectEdge = RectangleEdge.BOTTOM;
                    break;
                }
                legend.setPosition(legendRectEdge);
            }
            if (showSlicer) {
                RectangleEdge slicerRectPos = RectangleEdge.BOTTOM;
                HorizontalAlignment slicerHorizAlignment = HorizontalAlignment.LEFT;

                switch (slicerPosition) {
                case 0:
                    slicerRectPos = RectangleEdge.TOP;
                    break;
                case 1:
                    slicerRectPos = RectangleEdge.BOTTOM;
                    break;
                case 2:
                    slicerRectPos = RectangleEdge.RIGHT;
                    break;
                case 3:
                    slicerRectPos = RectangleEdge.LEFT;
                    break;
                }

                switch (slicerAlignment) {
                case 4:
                    slicerHorizAlignment = HorizontalAlignment.CENTER;
                    break;
                case 3:
                    slicerHorizAlignment = HorizontalAlignment.LEFT;
                    break;
                case 2:
                    slicerHorizAlignment = HorizontalAlignment.RIGHT;
                    break;
                }
                TextTitle slicer = new TextTitle(buildSlicer(), slicerFont, Color.BLACK, slicerRectPos,
                        slicerHorizAlignment, VerticalAlignment.CENTER, new RectangleInsets(0, 0, 0, 0));

                slicer.setPosition(slicerRectPos);
                chart.addSubtitle(slicer);
            }
            info = new ChartRenderingInfo(new StandardEntityCollection());
            //  Write the chart image to the temporary directory
            HttpSession session = context.getSession();
            filename = ServletUtilities.saveChartAsPNG(chart, chartWidth, chartHeight, info, session);

        } catch (Exception e) {
            filename = "public_error_500x300.png";
            dirty = true;
        }
    }
    // new DOM document
    DocumentBuilder parser = XmlUtils.getParser();
    // get an image map for the chart, wrap it in xchart tags
    String xchart = "<xchart>" + writeImageMap(filename, info, false) + "</xchart>";
    /*
          if (logger.isDebugEnabled()) {
             logger.debug("Chart XML");
             logger.debug(xchart);
          }
    */
    // create an InputStream from the DOM document
    InputStream stream = new ByteArrayInputStream(xchart.getBytes("UTF-8"));

    document = parser.parse(stream);
    Element root = document.getDocumentElement();
    // create url for img tag
    String graphURL = getGraphURL(context);

    Element img = document.createElement("img");
    img.setAttribute("src", graphURL);
    img.setAttribute("width", new Integer(chartWidth).toString());
    img.setAttribute("height", new Integer(chartHeight).toString());
    img.setAttribute("style", "border:0;");
    img.setAttribute("usemap", "#" + filename);
    root.appendChild(img);

    return document;
}

From source file:org.jfree.chart.ChartFactory.java

/**
 * Creates a pie chart with default settings that compares 2 datasets.
 * The color of each section will be determined by the move from the value
 * for the same key in {@code previousDataset}. ie if value1 &gt; value2
 * then the section will be in green (unless {@code greenForIncrease}
 * is {@code false}, in which case it would be {@code red}).
 * 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  ww  . j a va 2  s .com
 * <p>
 * For instance if {@code percentDiffForMaxScale} 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} permitted).
 * @param dataset  the dataset for the chart ({@code null} 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 locale  the locale ({@code null} not permitted).
 * @param subTitle displays a subtitle with color 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, 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));

    plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));

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

    double colorPerPercent = 255.0 / percentDiffForMaxScale;
    for (Comparable key : keys) {
        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) {
                assert series != null; // suppress compiler warning
                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) {
                assert series != null; // suppress compiler warning
                series.setValue(
                        key + " (" + (percentChange >= 0 ? "+" : "")
                                + NumberFormat.getPercentInstance().format(percentChange / 100.0) + ")",
                        newValue);
            }
        }
    }

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

    JFreeChart chart = new JFreeChart(title, plot);

    if (subTitle) {
        TextTitle 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.jfree.chart.ChartFactory.java

/**
 * Creates a pie chart with default settings that compares 2 datasets.
 * The color of each section will be determined by the move from the value
 * for the same key in {@code previousDataset}. ie if value1 &gt; value2
 * then the section will be in green (unless {@code greenForIncrease}
 * is {@code false}, in which case it would be {@code red}).
 * 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 . ja v  a  2 s  .  c  o  m*/
 * <p>
 * For instance if {@code percentDiffForMaxScale} 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} permitted).
 * @param dataset  the dataset for the chart ({@code null} 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 subTitle displays a subtitle with color 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 subTitle, boolean showDifference) {

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

    plot.setToolTipGenerator(new StandardPieToolTipGenerator());

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

    double colorPerPercent = 255.0 / percentDiffForMaxScale;
    for (Comparable key : keys) {
        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) {
                assert series != null; // suppresses compiler warning
                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) {
                assert series != null; // suppresses compiler warning
                series.setValue(
                        key + " (" + (percentChange >= 0 ? "+" : "")
                                + NumberFormat.getPercentInstance().format(percentChange / 100.0) + ")",
                        newValue);
            }
        }
    }

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

    JFreeChart chart = new JFreeChart(title, plot);

    if (subTitle) {
        TextTitle subtitle;
        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;
}