Example usage for org.jfree.chart.axis CategoryAxis setCategoryLabelPositions

List of usage examples for org.jfree.chart.axis CategoryAxis setCategoryLabelPositions

Introduction

In this page you can find the example usage for org.jfree.chart.axis CategoryAxis setCategoryLabelPositions.

Prototype

public void setCategoryLabelPositions(CategoryLabelPositions positions) 

Source Link

Document

Sets the category label position specification for the axis and sends an AxisChangeEvent to all registered listeners.

Usage

From source file:com.devoteam.srit.xmlloader.core.report.derived.DerivedCounter.java

public JFreeChart getHistogramChart() {

    double[] hits = this.counter.histogramDataset.getHistogramArray();
    double[] intervals = this.counter.histogramDataset.histogramParameters.histogramIntervals;
    double hitsCount = this.counter.histogramDataset.hits;
    DefaultCategoryDataset datasetNormal = new DefaultCategoryDataset();

    datasetNormal.addValue(0, "a", "          -INF");
    datasetNormal.addValue(0, "b", "          -INF");

    double cumul = 0;
    for (int i = 0; i < intervals.length - 1; i++) {
        String intervalName;/*from   w  w w.j  a v  a2 s .c  om*/

        if (i == intervals.length - 2) {
            intervalName = "          +INF";
        } else {
            intervalName = "          " + Double.toString(intervals[i + 1]);
        }

        cumul += hits[i];
        datasetNormal.addValue((100 * hits[i]) / hitsCount, "a", intervalName);
        datasetNormal.addValue((100 * cumul) / hitsCount, "b", intervalName);
    }

    JFreeChart jFreeChart = ChartFactory.createBarChart("", "", "%", datasetNormal, PlotOrientation.VERTICAL,
            false, false, false);

    CategoryPlot plot = jFreeChart.getCategoryPlot();
    CategoryAxis axis = plot.getDomainAxis();
    LayeredBarRenderer layeredBarRenderer = new LayeredBarRenderer();
    layeredBarRenderer.setSeriesPaint(0, new Color(0, 0, 255, 85));
    layeredBarRenderer.setSeriesPaint(1, new Color(255, 0, 0, 85));
    plot.setRenderer(layeredBarRenderer);

    plot.setRowRenderingOrder(SortOrder.DESCENDING);
    axis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
    axis.setMaximumCategoryLabelWidthRatio(1);

    jFreeChart.setBackgroundPaint(Color.WHITE);
    return jFreeChart;

}

From source file:hudson.plugins.plot.PlotData.java

/**
 * Generates the plot and stores it in the plot instance variable.
 * //from www  .j a v a 2s.  c o  m
 * @param forceGenerate if true, force the plot to be re-generated
 *        even if the on-disk data hasn't changed
 */
private void generatePlot(boolean forceGenerate) {
    class Label implements Comparable<Label> {
        final private Integer buildNum;
        final private String buildDate;
        final private String text;

        public Label(String buildNum, String buildTime, String text) {
            this.buildNum = Integer.parseInt(buildNum);
            synchronized (DATE_FORMAT) {
                this.buildDate = DATE_FORMAT.format(new Date(Long.parseLong(buildTime)));
            }
            this.text = text;
        }

        public int compareTo(Label that) {
            return this.buildNum - that.buildNum;
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Label && ((Label) o).buildNum.equals(buildNum);
        }

        @Override
        public int hashCode() {
            return buildNum.hashCode();
        }

        public String numDateString() {
            return "#" + buildNum + " (" + buildDate + ")";
        }

        @Override
        public String toString() {
            return text != null ? text : numDateString();
        }
    }
    LOGGER.fine("Generating plot from file: " + csvFilePath.getName());
    PlotCategoryDataset dataset = new PlotCategoryDataset();
    for (String[] record : rawPlotData) {
        // record: series y-value, series label, build number, build date, url
        int buildNum;
        try {
            buildNum = Integer.valueOf(record[2]);
            if (project.getBuildByNumber(buildNum) == null || buildNum > getRightBuildNum()) {
                continue; // skip this record
            }
        } catch (NumberFormatException nfe) {
            continue; // skip this record all together
        }
        Number value = null;
        try {
            value = Integer.valueOf(record[0]);
        } catch (NumberFormatException nfe) {
            try {
                value = Double.valueOf(record[0]);
            } catch (NumberFormatException nfe2) {
                continue; // skip this record all together
            }
        }
        String series = record[1];
        Label xlabel = getUrlUseDescr() ? new Label(record[2], record[3], descriptionForBuild(buildNum))
                : new Label(record[2], record[3], getBuildName(buildNum));
        String url = null;
        if (record.length >= 5)
            url = record[4];
        dataset.setValue(value, url, series, xlabel);
    }
    int numBuilds;
    try {
        numBuilds = Integer.parseInt(getURLNumBuilds());
    } catch (NumberFormatException nfe) {
        numBuilds = DEFAULT_NUMBUILDS;
    }
    dataset.clipDataset(numBuilds);
    plot = createChart(dataset);
    CategoryPlot categoryPlot = (CategoryPlot) plot.getPlot();
    categoryPlot.setDomainGridlinePaint(Color.black);
    categoryPlot.setRangeGridlinePaint(Color.black);
    categoryPlot.setDrawingSupplier(PlotData.supplier);
    CategoryAxis domainAxis = new ShiftedCategoryAxis(Messages.Plot_Build());
    categoryPlot.setDomainAxis(domainAxis);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.03);
    domainAxis.setCategoryMargin(0.0);
    for (Object category : dataset.getColumnKeys()) {
        Label label = (Label) category;
        if (label.text != null) {
            domainAxis.addCategoryLabelToolTip(label, label.numDateString());
        } else {
            domainAxis.addCategoryLabelToolTip(label, descriptionForBuild(label.buildNum));
        }
    }

    AbstractCategoryItemRenderer renderer = (AbstractCategoryItemRenderer) categoryPlot.getRenderer();
    int numColors = dataset.getRowCount();
    for (int i = 0; i < numColors; i++) {
        renderer.setSeriesPaint(i, new Color(Color.HSBtoRGB((1f / numColors) * i, 1f, 1f)));
    }
    renderer.setStroke(new BasicStroke(2.0f));
    renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator(Messages.Plot_Build() + " {1}: {2}",
            NumberFormat.getInstance()));
    renderer.setItemURLGenerator(new PointURLGenerator());
    if (renderer instanceof LineAndShapeRenderer) {
        LineAndShapeRenderer lasRenderer = (LineAndShapeRenderer) renderer;
        lasRenderer.setShapesVisible(true); // TODO: deprecated, may be unnecessary
    }
}

From source file:org.apache.jmeter.visualizers.CreateReport.java

/**
 * Creates a table; widths are set with setWidths().
 * @return a PdfPTable//  w  w w.  j a  va 2s.  c  o  m
 * @throws DocumentException
 */

//createGraphs("Average Response Time of samples for each Request","Average(ms)",2);
public Image createGraphs(String chartName, String colName, int colNo) {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (int i = 0; i < model.getRowCount(); i++)
        dataset.setValue((long) model.getValueAt(i, colNo), "Average", model.getValueAt(i, 0).toString());
    ChartFactory.setChartTheme(StandardChartTheme.createDarknessTheme());

    final JFreeChart chart = ChartFactory.createBarChart3D(chartName, // chart title
            "Requests", // domain axis label

            "Average (ms)", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    final CategoryPlot plot = chart.getCategoryPlot();
    final CategoryAxis axis = plot.getDomainAxis();
    axis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 8.0));
    final BarRenderer3D renderer = (BarRenderer3D) plot.getRenderer();
    renderer.setDrawBarOutline(false);
    renderer.setMaximumBarWidth(0.05);

    try {
        //java.io.OutputStream out= new OutputStream(new FileOutputStream(BASEPATH+"//MyFile.jpg"));
        ChartUtilities.saveChartAsJPEG(new File(BASEPATH + "//MyFile.jpg"), chart, 500, 400);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Image img = null;
    try {
        img = Image.getInstance(BASEPATH + "//MyFile.jpg");
    } catch (BadElementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return img;
}

From source file:com.manydesigns.portofino.chart.Chart2DGenerator.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  .j  av  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) {
        BarRenderer barRenderer = (BarRenderer) renderer;

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

    // 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);
    // ?
    plot.setForegroundAlpha(1.0f);
    // 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:View.DialogoEstadisticas.java

private void creaGraficaIndicadores(int selectedIndex) {
    EdoRes e;/*from w  w w  .  ja  va  2 s  .  c  om*/

    DefaultCategoryDataset dataset;
    CategoryPlot p;
    switch (selectedIndex) {
    case 0:
        if (rdIntervalo.isSelected()) {
            rdIntervalo.doClick();
        }
        DefaultPieDataset data = new DefaultPieDataset();
        data.setValue("Efectivo: " + uts.formatPorcentaje(i.getPorLiq()) + " ("
                + uts.formatDinero(i.getEfectivo()) + ")", i.getPorLiq());
        data.setValue("Clientes: " + uts.formatPorcentaje(i.getPorDebClientes()) + " ("
                + uts.formatDinero(i.getSaldoClientes()) + ")", i.getPorDebClientes());
        data.setValue("Deudores Div: " + uts.formatPorcentaje(i.getPorDebDiv()) + " ("
                + uts.formatDinero(i.getSaldoDeuDiv()) + ")", i.getPorDebDiv());
        data.setValue("Inversion: " + uts.formatPorcentaje(i.getPorInv()) + " ("
                + uts.formatDinero(i.getInversion()) + ")", i.getPorInv());
        // Creando el Grafico
        chart = ChartFactory.createPieChart("Distribucin de Activo", data, true, true, false);
        chart.setBackgroundPaint(Color.lightGray);

        break;
    case 1: //Efectivo
        // Fuente de Datos
        dataset = new DefaultCategoryDataset();
        for (Indicador ind : indicadores) {
            if (ind.getNombre().equals("Efectivo")) {
                if (combrobarIntervalo(ind.getPeriodo())) {
                    dataset.setValue(ind.getValor(), "Efectivo", formatPeriodo(ind.getPeriodo()));
                }
            }
        }

        // Creando el Grafico
        chart = ChartFactory.createBarChart3D("Flujo de Efectivo", "Efectivo", "Periodos", dataset,
                PlotOrientation.VERTICAL, true, true, false);
        chart.setBackgroundPaint(Color.lightGray);
        chart.getTitle().setPaint(Color.black);
        p = chart.getCategoryPlot();
        p.setRangeGridlinePaint(Color.blue);
        //titulos de eje y en vertical
        p = chart.getCategoryPlot();
        CategoryAxis domainAxis = ((CategoryPlot) p).getDomainAxis();
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
        break;

    case 2: //Margen
        // Fuente de Datos
        dataset = new DefaultCategoryDataset();
        h.buscaPeriodos();
        String[] periodos = h.getPeriodos();
        for (String per : periodos) {
            if (combrobarIntervalo(per)) {
                System.out.println("------------------SI");
                e = new EdoRes(per);
                dataset.setValue(e.getMargen(), formatPeriodo(per) + ": %" + uts.format2(e.getMargen()),
                        formatPeriodo(per));
            } else {

                System.out.println("-" + per + "-----NO");
            }
        }
        // Creando el Grafico
        chart = ChartFactory.createBarChart3D("Margen de ganancia", "margen (%)", "periodos", dataset,
                PlotOrientation.VERTICAL, true, true, false);
        chart.setBackgroundPaint(Color.lightGray);
        chart.getTitle().setPaint(Color.black);
        p = chart.getCategoryPlot();
        p.setRangeGridlinePaint(Color.blue);
        //titulos de eje y en vertical
        p = chart.getCategoryPlot();
        CategoryAxis domainAxis2 = ((CategoryPlot) p).getDomainAxis();
        domainAxis2.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
        break;

    }

    chartPanel = new ChartPanel(chart);
    chartPanel.setVisible(true);
    chartPanel.setSize(723, 456);
    panelG.add(chartPanel);
    panelG.revalidate();
    panelG.repaint();
}

From source file:edu.ucla.stat.SOCR.chart.demo.CategoryStepChartDemo1.java

/**
 * Creates a chart./*w  w  w .ja va 2 s . c  o  m*/
 * 
 * @param dataset  the dataset.
 * 
 * @return The chart.
 */
protected JFreeChart createChart(CategoryDataset dataset) {

    CategoryItemRenderer renderer = new CategoryStepRenderer(true);

    CategoryAxis domainAxis = new CategoryAxis(domainLabel);
    NumberAxis rangeAxis = new NumberAxis(rangeLabel);
    CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
    JFreeChart chart = new JFreeChart(chartTitle, plot);

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
    chart.setBackgroundPaint(Color.white);

    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.white);

    AbstractCategoryItemRenderer renderer2 = (AbstractCategoryItemRenderer) plot.getRenderer();
    renderer2.setLegendItemLabelGenerator(new SOCRCategorySeriesLabelGenerator());

    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    domainAxis.addCategoryLabelToolTip("Type 1", "The first type.");
    domainAxis.addCategoryLabelToolTip("Type 2", "The second type.");
    domainAxis.addCategoryLabelToolTip("Type 3", "The third type.");

    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setLabelAngle(0 * Math.PI / 2.0);
    // OPTIONAL CUSTOMISATION COMPLETED.

    setCategorySummary(dataset);
    if (legendPanelOn)
        chart.removeLegend();
    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   w ww. java2  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:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.StackedBar.java

/**
 * Inherited by IChart./*from   ww w . ja  v a 2s .  c o m*/
 * 
 * @param chartTitle the chart title
 * @param dataset the dataset
 * 
 * @return the j free chart
 */

public JFreeChart createChart(DatasetMap datasets) {

    logger.debug("IN");
    CategoryDataset dataset = (CategoryDataset) datasets.getDatasets().get("1");

    logger.debug("Taken Dataset");

    logger.debug("Get plot orientaton");
    PlotOrientation plotOrientation = PlotOrientation.VERTICAL;
    if (horizontalView) {
        plotOrientation = PlotOrientation.HORIZONTAL;
    }

    logger.debug("Call Chart Creation");
    JFreeChart chart = ChartFactory.createStackedBarChart(name, // chart title
            categoryLabel, // domain axis label
            valueLabel, // range axis label
            dataset, // data
            plotOrientation, // the plot orientation
            false, // legend
            true, // tooltips
            false // urls
    );
    logger.debug("Chart Created");

    chart.setBackgroundPaint(Color.white);
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(color);
    plot.setRangeGridlinePaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setDomainGridlinesVisible(true);

    logger.debug("set renderer");
    StackedBarRenderer renderer = (StackedBarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);
    renderer.setBaseItemLabelsVisible(true);

    if (percentageValue)
        renderer.setBaseItemLabelGenerator(
                new StandardCategoryItemLabelGenerator("{2}", new DecimalFormat("#,##.#%")));
    else if (makePercentage)
        renderer.setRenderAsPercentages(true);

    /*
    else
       renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
     */
    renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());

    if (maxBarWidth != null) {
        renderer.setMaximumBarWidth(maxBarWidth.doubleValue());
    }

    boolean document_composition = false;
    if (mode.equalsIgnoreCase(SpagoBIConstants.DOCUMENT_COMPOSITION))
        document_composition = true;

    logger.debug("Calling Url Generation");

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

        mycatUrl.setDocument_composition(document_composition);
        mycatUrl.setCategoryUrlLabel(categoryUrlName);
        mycatUrl.setSerieUrlLabel(serieUrlname);
    }
    if (mycatUrl != null)
        renderer.setItemURLGenerator(mycatUrl);

    logger.debug("Text Title");

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

    logger.debug("Style Labels");

    Color colorSubInvisibleTitle = Color.decode("#FFFFFF");
    StyleLabel styleSubSubTitle = new StyleLabel("Arial", 12, colorSubInvisibleTitle);
    TextTitle subsubTitle = setStyleTitle("", styleSubSubTitle);
    chart.addSubtitle(subsubTitle);
    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

    // set the background color for the chart...
    chart.setBackgroundPaint(color);

    logger.debug("Axis creation");
    // set the range axis to display integers only...

    NumberFormat nf = NumberFormat.getNumberInstance(locale);

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    if (makePercentage)
        rangeAxis.setNumberFormatOverride(NumberFormat.getPercentInstance());
    else
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    if (rangeIntegerValues == true) {
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }

    rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setLabelPaint(styleXaxesLabels.getColor());
    rangeAxis
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor());
    rangeAxis.setNumberFormatOverride(nf);

    if (rangeAxisLocation != null) {
        if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_LEFT")) {
            plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_LEFT);
        } else if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_RIGHT")) {
            plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_RIGHT);
        } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_RIGHT")) {
            plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_RIGHT);
        } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_LEFT")) {
            plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_LEFT);
        }
    }

    renderer.setDrawBarOutline(false);

    logger.debug("Set series color");

    int seriesN = dataset.getRowCount();
    if (orderColorVector != null && orderColorVector.size() > 0) {
        logger.debug("color serie by SERIES_ORDER_COLORS template specification");
        for (int i = 0; i < seriesN; i++) {
            if (orderColorVector.get(i) != null) {
                Color color = orderColorVector.get(i);
                renderer.setSeriesPaint(i, color);
            }
        }
    } else if (colorMap != null) {
        for (int i = 0; i < seriesN; i++) {
            String serieName = (String) dataset.getRowKey(i);

            // if serie has been rinominated I must search with the new name!
            String nameToSearchWith = (seriesLabelsMap != null && seriesLabelsMap.containsKey(serieName))
                    ? seriesLabelsMap.get(serieName).toString()
                    : serieName;

            Color color = (Color) colorMap.get(nameToSearchWith);
            if (color != null) {
                renderer.setSeriesPaint(i, color);
                renderer.setSeriesItemLabelFont(i,
                        new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
            }
        }
    }

    logger.debug("If cumulative set series paint " + cumulative);

    if (cumulative) {
        int row = dataset.getRowIndex("CUMULATIVE");
        if (row != -1) {
            if (color != null)
                renderer.setSeriesPaint(row, color);
            else
                renderer.setSeriesPaint(row, Color.WHITE);
        }
    }

    MyStandardCategoryItemLabelGenerator generator = null;
    logger.debug("Are there addition labels " + additionalLabels);
    logger.debug("Are there value labels " + showValueLabels);

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

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

        generator = new MyStandardCategoryItemLabelGenerator(catSerLabels, "{1}", NumberFormat.getInstance());
        logger.debug("generator set");

        double orient = (-Math.PI / 2.0);
        logger.debug("add labels style");
        if (styleValueLabels.getOrientation() != null
                && styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) {
            orient = 0.0;
        }
        renderer.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        renderer.setBaseItemLabelPaint(styleValueLabels.getColor());

        logger.debug("add labels style set");

        renderer.setBaseItemLabelGenerator(generator);
        renderer.setBaseItemLabelsVisible(true);
        //vertical labels          
        renderer.setBasePositiveItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER, TextAnchor.CENTER, orient));
        renderer.setBaseNegativeItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER, TextAnchor.CENTER, orient));

        logger.debug("end of add labels ");

    }

    logger.debug("domain axis");

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 4.0));
    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());
    //opacizzazione colori
    if (!cumulative)
        plot.setForegroundAlpha(0.6f);
    if (legend == true)
        drawLegend(chart);

    logger.debug("OUT");
    return chart;

}

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 ww  . 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) {
        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:org.jfree.chart.demo.CategoryStepChartDemo.java

/**
 * Creates a chart./*from   w  w  w. j a v a  2s.c o  m*/
 * 
 * @param dataset  the dataset.
 * 
 * @return The chart.
 */
private JFreeChart createChart(final CategoryDataset dataset) {

    final CategoryItemRenderer renderer = new CategoryStepRenderer(true);
    final CategoryAxis domainAxis = new CategoryAxis("Category");
    final ValueAxis rangeAxis = new NumberAxis("Value");
    final CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
    final JFreeChart chart = new JFreeChart("Category Step Chart", plot);

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

    // set the background color for the chart...
    //        final StandardLegend legend = (StandardLegend) chart.getLegend();
    //      legend.setAnchor(StandardLegend.SOUTH);

    chart.setBackgroundPaint(Color.white);

    //        plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.white);

    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    domainAxis.addCategoryLabelToolTip("Type 1", "The first type.");
    domainAxis.addCategoryLabelToolTip("Type 2", "The second type.");
    domainAxis.addCategoryLabelToolTip("Type 3", "The third type.");

    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setLabelAngle(0 * Math.PI / 2.0);
    // OPTIONAL CUSTOMISATION COMPLETED.

    return chart;

}