Example usage for org.jfree.chart JFreeChart getLegend

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

Introduction

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

Prototype

public LegendTitle getLegend() 

Source Link

Document

Returns the legend for the chart, if there is one.

Usage

From source file:gov.nih.nci.rembrandt.web.graphing.data.GeneExpressionPlot.java

public static HashMap generateBarChart(String gene, String reporter, HttpSession session, PrintWriter pw,
        GeneExpressionDataSetType geType) {
    String log2Filename = null;/* w w w .  ja  va2  s .co m*/
    String rawFilename = null;
    String medianFilename = null;
    String bwFilename = "";
    String legendHtml = null;
    HashMap charts = new HashMap();
    PlotSize ps = PlotSize.MEDIUM;

    final String geneName = gene;
    final String alg = geType.equals(GeneExpressionDataSetType.GeneExpressionDataSet)
            ? RembrandtConstants.REPORTER_SELECTION_AFFY
            : RembrandtConstants.REPORTER_SELECTION_UNI;
    try {
        InstitutionCriteria institutionCriteria = InsitutionAccessHelper.getInsititutionCriteria(session);

        final GenePlotDataSet gpds = new GenePlotDataSet(gene, reporter, institutionCriteria, geType,
                session.getId());
        //final GenePlotDataSet gpds = new GenePlotDataSet(gene, institutionCriteria,GeneExpressionDataSetType.GeneExpressionDataSet );

        //LOG2 Dataset
        DefaultStatisticalCategoryDataset dataset = (DefaultStatisticalCategoryDataset) gpds.getLog2Dataset();

        //RAW Dataset
        CategoryDataset meanDataset = (CategoryDataset) gpds.getRawDataset();

        //B&W dataset
        DefaultBoxAndWhiskerCategoryDataset bwdataset = (DefaultBoxAndWhiskerCategoryDataset) gpds
                .getBwdataset();

        //Median dataset
        CategoryDataset medianDataset = (CategoryDataset) gpds.getMedianDataset();

        charts.put("diseaseSampleCountMap", gpds.getDiseaseSampleCountMap());

        //IMAGE Size Control
        if (bwdataset != null && bwdataset.getRowCount() > 5) {
            ps = PlotSize.LARGE;
        } else {
            ps = PlotSize.MEDIUM;
        }
        //SMALL/MEDIUM == 650 x 400
        //LARGE == 1000 x 400
        //put as external Props?
        int imgW = 650;
        if (ps == PlotSize.LARGE) {
            imgW = new BigDecimal(bwdataset.getRowCount()).multiply(new BigDecimal(75)).intValue() > 1000
                    ? new BigDecimal(bwdataset.getRowCount()).multiply(new BigDecimal(75)).intValue()
                    : 1000;
        }

        JFreeChart bwChart = null;

        //B&W plot
        CategoryAxis xAxis = new CategoryAxis("Disease Type");
        NumberAxis yAxis = new NumberAxis("Log2 Expression Intensity");
        yAxis.setAutoRangeIncludesZero(true);
        BoxAndWhiskerCoinPlotRenderer bwRenderer = null;
        // BoxAndWhiskerRenderer bwRenderer = new BoxAndWhiskerRenderer();
        if (reporter != null) {
            //single reporter, show the coins
            bwRenderer = new BoxAndWhiskerCoinPlotRenderer(gpds.getCoinHash());
            bwRenderer.setDisplayCoinCloud(true);
            bwRenderer.setDisplayMean(false);
            bwRenderer.setDisplayAllOutliers(true);
            bwRenderer.setToolTipGenerator(new CategoryToolTipGenerator() {
                public String generateToolTip(CategoryDataset dataset, int series, int item) {
                    String tt = "";
                    NumberFormat formatter = new DecimalFormat(".####");
                    String key = "";
                    //String s = formatter.format(-1234.567);  // -001235
                    if (dataset instanceof DefaultBoxAndWhiskerCategoryDataset) {
                        DefaultBoxAndWhiskerCategoryDataset ds = (DefaultBoxAndWhiskerCategoryDataset) dataset;
                        try {
                            String med = formatter.format(ds.getMedianValue(series, item));
                            tt += "Median: " + med + "<br/>";
                            tt += "Mean: " + formatter.format(ds.getMeanValue(series, item)) + "<br/>";
                            tt += "Q1: " + formatter.format(ds.getQ1Value(series, item)) + "<br/>";
                            tt += "Q3: " + formatter.format(ds.getQ3Value(series, item)) + "<br/>";
                            tt += "Max: " + formatter.format(
                                    FaroutOutlierBoxAndWhiskerCalculator.getMaxFaroutOutlier(ds, series, item))
                                    + "<br/>";
                            tt += "Min: " + formatter.format(
                                    FaroutOutlierBoxAndWhiskerCalculator.getMinFaroutOutlier(ds, series, item))
                                    + "<br/>";
                            //tt += "<br/><br/>Please click on the box and whisker to view a plot for this reporter.<br/>";
                            //tt += "X: " + ds.getValue(series, item).toString()+"<br/>";
                            //tt += "<br/><a href=\\\'#\\\' id=\\\'"+ds.getRowKeys().get(series)+"\\\' onclick=\\\'alert(this.id);return false;\\\'>"+ds.getRowKeys().get(series)+" plot</a><br/><br/>";
                            key = ds.getRowKeys().get(series).toString();
                        } catch (Exception e) {
                        }
                    }

                    return tt;
                }

            });
        } else {
            //groups, dont show coins
            bwRenderer = new BoxAndWhiskerCoinPlotRenderer();
            bwRenderer.setDisplayAllOutliers(true);
            bwRenderer.setToolTipGenerator(new CategoryToolTipGenerator() {
                public String generateToolTip(CategoryDataset dataset, int series, int item) {
                    String tt = "";
                    NumberFormat formatter = new DecimalFormat(".####");
                    String key = "";
                    //String s = formatter.format(-1234.567);  // -001235
                    if (dataset instanceof DefaultBoxAndWhiskerCategoryDataset) {
                        DefaultBoxAndWhiskerCategoryDataset ds = (DefaultBoxAndWhiskerCategoryDataset) dataset;
                        try {
                            String med = formatter.format(ds.getMedianValue(series, item));
                            tt += "Median: " + med + "<br/>";
                            tt += "Mean: " + formatter.format(ds.getMeanValue(series, item)) + "<br/>";
                            tt += "Q1: " + formatter.format(ds.getQ1Value(series, item)) + "<br/>";
                            tt += "Q3: " + formatter.format(ds.getQ3Value(series, item)) + "<br/>";
                            tt += "Max: " + formatter.format(
                                    FaroutOutlierBoxAndWhiskerCalculator.getMaxFaroutOutlier(ds, series, item))
                                    + "<br/>";
                            tt += "Min: " + formatter.format(
                                    FaroutOutlierBoxAndWhiskerCalculator.getMinFaroutOutlier(ds, series, item))
                                    + "<br/>";
                            tt += "<br/><br/>Please click on the box and whisker to view a plot for this reporter.<br/>";
                            //tt += "X: " + ds.getValue(series, item).toString()+"<br/>";
                            //tt += "<br/><a href=\\\'#\\\' id=\\\'"+ds.getRowKeys().get(series)+"\\\' onclick=\\\'alert(this.id);return false;\\\'>"+ds.getRowKeys().get(series)+" plot</a><br/><br/>";
                            key = ds.getRowKeys().get(series).toString();
                        } catch (Exception e) {
                        }
                    }
                    return "onclick=\"popCoin('" + geneName + "','" + key + "', '" + alg + "');\" | " + tt;

                }

            });
        }
        bwRenderer.setFillBox(false);

        CategoryPlot bwPlot = new CategoryPlot(bwdataset, xAxis, yAxis, bwRenderer);
        bwChart = new JFreeChart(bwPlot);

        //    JFreeChart bwChart = new JFreeChart(
        //       null /*"Gene Expression Plot (" + gene.toUpperCase() + ")"*/,
        //        new Font("SansSerif", Font.BOLD, 14),
        //        bwPlot,
        //        true
        //    );

        bwChart.setBackgroundPaint(java.awt.Color.white);
        //bwChart.getTitle().setHorizontalAlignment(TextTitle.DEFAULT_HORIZONTAL_ALIGNMENT.LEFT);

        bwChart.removeLegend();
        //END BW plot

        // create the chart...for LOG2 dataset
        JFreeChart log2Chart = ChartFactory.createBarChart(
                null /*"Gene Expression Plot (" + gene.toUpperCase() + ")"*/, // chart
                // title
                "Groups", // domain axis label
                "Log2 Expression Intensity", // range axis label
                dataset, // data
                PlotOrientation.VERTICAL, // orientation
                true, // include legend
                true, // tooltips?
                false // URLs?
        );

        //create the chart .... for RAW dataset
        JFreeChart meanChart = ChartFactory.createBarChart(
                null /*"Gene Expression Plot (" + gene.toUpperCase() + ")"*/, // chart
                // title
                "Groups", // domain axis label
                "Mean Expression Intensity", // range axis label
                meanDataset, // data
                PlotOrientation.VERTICAL, // orientation
                true, // include legend
                true, // tooltips?
                false // URLs?
        );

        //         create the chart .... for Median dataset
        JFreeChart medianChart = ChartFactory.createBarChart(
                null /*"Gene Expression Plot (" + gene.toUpperCase() + ")"*/, // chart
                // title
                "Groups", // domain axis label
                "Median Expression Intensity", // range axis label
                medianDataset, // data
                PlotOrientation.VERTICAL, // orientation
                true, // include legend
                true, // tooltips?
                false // URLs?
        );

        log2Chart.setBackgroundPaint(java.awt.Color.white);
        // lets start some customization to retro fit w/jcharts lookand feel
        CategoryPlot log2Plot = log2Chart.getCategoryPlot();
        CategoryAxis log2Axis = log2Plot.getDomainAxis();
        log2Axis.setLowerMargin(0.02); // two percent
        log2Axis.setCategoryMargin(0.20); // 20 percent
        log2Axis.setUpperMargin(0.02); // two percent

        // same for our fake chart - just to get the tooltips
        meanChart.setBackgroundPaint(java.awt.Color.white);
        CategoryPlot meanPlot = meanChart.getCategoryPlot();
        CategoryAxis meanAxis = meanPlot.getDomainAxis();
        meanAxis.setLowerMargin(0.02); // two percent
        meanAxis.setCategoryMargin(0.20); // 20 percent
        meanAxis.setUpperMargin(0.02); // two percent

        //   median plot
        medianChart.setBackgroundPaint(java.awt.Color.white);
        CategoryPlot medianPlot = medianChart.getCategoryPlot();
        CategoryAxis medianAxis = medianPlot.getDomainAxis();
        medianAxis.setLowerMargin(0.02); // two percent
        medianAxis.setCategoryMargin(0.20); // 20 percent
        medianAxis.setUpperMargin(0.02); // two percent

        // customise the renderer...
        StatisticalBarRenderer log2Renderer = new StatisticalBarRenderer();

        // BarRenderer renderer = (BarRenderer) plot.getRenderer();
        log2Renderer.setItemMargin(0.01); // one percent
        log2Renderer.setDrawBarOutline(true);
        log2Renderer.setOutlinePaint(Color.BLACK);
        log2Renderer.setToolTipGenerator(new CategoryToolTipGenerator() {

            public String generateToolTip(CategoryDataset dataset, int series, int item) {
                HashMap pv = gpds.getPValuesHashMap();
                HashMap std_d = gpds.getStdDevMap();

                String currentPV = (String) pv
                        .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item));
                String stdDev = (String) std_d
                        .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item));

                return "Probeset : " + dataset.getRowKey(series) + "<br/>Intensity : "
                        + new DecimalFormat("0.0000").format(dataset.getValue(series, item)) + "<br/>"
                        + RembrandtConstants.PVALUE + " : " + currentPV + "<br/>Std. Dev.: " + stdDev + "<br/>";
            }

        });
        log2Plot.setRenderer(log2Renderer);
        // customize the  renderer
        BarRenderer meanRenderer = (BarRenderer) meanPlot.getRenderer();
        meanRenderer.setItemMargin(0.01); // one percent
        meanRenderer.setDrawBarOutline(true);
        meanRenderer.setOutlinePaint(Color.BLACK);
        meanRenderer.setToolTipGenerator(new CategoryToolTipGenerator() {

            public String generateToolTip(CategoryDataset dataset, int series, int item) {
                HashMap pv = gpds.getPValuesHashMap();
                HashMap std_d = gpds.getStdDevMap();
                String currentPV = (String) pv
                        .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item));

                String stdDev = (String) std_d
                        .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item));

                return "Probeset : " + dataset.getRowKey(series) + "<br/>Intensity : "
                        + new DecimalFormat("0.0000").format(dataset.getValue(series, item)) + "<br/>"
                        + RembrandtConstants.PVALUE + ": " + currentPV + "<br/>";
                //"<br/>Std. Dev.: " + stdDev + "<br/>";
            }

        });

        meanPlot.setRenderer(meanRenderer);
        // customize the  renderer
        BarRenderer medianRenderer = (BarRenderer) medianPlot.getRenderer();
        medianRenderer.setItemMargin(0.01); // one percent
        medianRenderer.setDrawBarOutline(true);
        medianRenderer.setOutlinePaint(Color.BLACK);
        medianRenderer.setToolTipGenerator(new CategoryToolTipGenerator() {

            public String generateToolTip(CategoryDataset dataset, int series, int item) {
                HashMap pv = gpds.getPValuesHashMap();
                HashMap std_d = gpds.getStdDevMap();
                String currentPV = (String) pv
                        .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item));

                String stdDev = (String) std_d
                        .get(dataset.getRowKey(series) + "::" + dataset.getColumnKey(item));

                return "Probeset : " + dataset.getRowKey(series) + "<br/>Intensity : "
                        + new DecimalFormat("0.0000").format(dataset.getValue(series, item)) + "<br/>"
                        + RembrandtConstants.PVALUE + ": " + currentPV + "<br/>";
                //"<br/>Std. Dev.: " + stdDev + "<br/>";
            }

        });

        // LegendTitle lg = chart.getLegend();

        medianPlot.setRenderer(medianRenderer);
        // lets generate a custom legend - assumes theres only one source?
        LegendItemCollection lic = log2Chart.getLegend().getSources()[0].getLegendItems();
        legendHtml = LegendCreator.buildLegend(lic, "Probesets");

        log2Chart.removeLegend();
        meanChart.removeLegend();
        medianChart.removeLegend();

        //bwChart.removeLegend(); // <-- do this above

        // Write the chart image to the temporary directory
        ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

        // BW
        if (bwChart != null) {
            int bwwidth = new BigDecimal(1.5).multiply(new BigDecimal(imgW)).intValue();
            bwFilename = ServletUtilities.saveChartAsPNG(bwChart, bwwidth, 400, info, session);
            CustomOverlibToolTipTagFragmentGenerator ttip = new CustomOverlibToolTipTagFragmentGenerator();
            String toolTip = " href='javascript:void(0);' alt='GeneChart JFreechart Plot' ";
            ttip.setExtra(toolTip); //must have href for area tags to have cursor:pointer
            ChartUtilities.writeImageMap(pw, bwFilename, info, ttip, new StandardURLTagFragmentGenerator());
            info.clear(); // lose the first one
            info = new ChartRenderingInfo(new StandardEntityCollection());
        }
        //END  BW
        log2Filename = ServletUtilities.saveChartAsPNG(log2Chart, imgW, 400, info, session);
        CustomOverlibToolTipTagFragmentGenerator ttip = new CustomOverlibToolTipTagFragmentGenerator();
        String toolTip = " alt='GeneChart JFreechart Plot' ";
        ttip.setExtra(toolTip); //must have href for area tags to have cursor:pointer
        ChartUtilities.writeImageMap(pw, log2Filename, info, ttip, new StandardURLTagFragmentGenerator());
        // clear the first one and overwrite info with our second one - no
        // error bars
        info.clear(); // lose the first one
        info = new ChartRenderingInfo(new StandardEntityCollection());
        rawFilename = ServletUtilities.saveChartAsPNG(meanChart, imgW, 400, info, session);
        // Write the image map to the PrintWriter
        // can use a different writeImageMap to pass tooltip and URL custom
        ttip = new CustomOverlibToolTipTagFragmentGenerator();
        toolTip = " alt='GeneChart JFreechart Plot' ";
        ttip.setExtra(toolTip); //must have href for area tags to have cursor:pointer
        ChartUtilities.writeImageMap(pw, rawFilename, info, ttip, new StandardURLTagFragmentGenerator());

        info.clear(); // lose the first one
        info = new ChartRenderingInfo(new StandardEntityCollection());
        medianFilename = ServletUtilities.saveChartAsPNG(medianChart, imgW, 400, info, session);

        // Write the image map to the PrintWriter
        // can use a different writeImageMap to pass tooltip and URL custom
        ttip = new CustomOverlibToolTipTagFragmentGenerator();
        toolTip = " alt='GeneChart JFreechart Plot' ";
        ttip.setExtra(toolTip); //must have href for area tags to have cursor:pointer
        ChartUtilities.writeImageMap(pw, medianFilename, info, ttip, new StandardURLTagFragmentGenerator());

        // ChartUtilities.writeImageMap(pw, filename, info, true);

        pw.flush();

    } catch (Exception e) {
        System.out.println("Exception - " + e.toString());
        e.printStackTrace(System.out);
        log2Filename = "public_error_500x300.png";
    }
    // return filename;
    charts.put("errorBars", log2Filename);
    charts.put("noErrorBars", rawFilename);
    charts.put("medianBars", medianFilename);
    charts.put("bwFilename", bwFilename);
    charts.put("legend", legendHtml);
    charts.put("size", ps.toString());

    return charts;
}

From source file:interfaces.InterfazPrincipal.java

private void botonGenerarReporteClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botonGenerarReporteClienteActionPerformed
    // TODO add your handling code here:
    try {//from w  w  w .j  av  a 2s  .co m
        if (clienteReporteClienteFechaFinal.getSelectedDate().getTime()
                .compareTo(clienteReporteClienteFechaInicial.getSelectedDate().getTime()) < 0) {
            JOptionPane.showMessageDialog(this, "La fecha final debe ser posterior al dia de inicio");
        } else {
            final ArrayList<Integer> listaIDFlujos = new ArrayList<>();
            final JDialog dialogoEditar = new JDialog();
            dialogoEditar.setTitle("Reporte cliente");
            dialogoEditar.setSize(350, 610);
            dialogoEditar.setResizable(false);

            JPanel panelDialogo = new JPanel();
            panelDialogo.setLayout(new GridBagLayout());

            GridBagConstraints c = new GridBagConstraints();
            //c.fill = GridBagConstraints.HORIZONTAL;

            JLabel ediitarTextoPrincipalDialogo = new JLabel("Informe cliente");
            c.gridx = 0;
            c.gridy = 0;
            c.gridwidth = 1;
            c.insets = new Insets(10, 45, 10, 10);
            Font textoGrande = new Font("Arial", 1, 18);
            ediitarTextoPrincipalDialogo.setFont(textoGrande);
            panelDialogo.add(ediitarTextoPrincipalDialogo, c);

            final JTable tablaDialogo = new JTable();
            DefaultTableModel modeloTabla = new DefaultTableModel() {

                @Override
                public boolean isCellEditable(int row, int column) {
                    //all cells false
                    return false;
                }
            };
            ;

            modeloTabla.addColumn("Factura");
            modeloTabla.addColumn("Tipo Flujo");
            modeloTabla.addColumn("Fecha");
            modeloTabla.addColumn("Valor");

            //Llenar tabla
            ControladorFlujoFactura controladorFlujoFactura = new ControladorFlujoFactura();
            ArrayList<String[]> flujosCliente = controladorFlujoFactura.getTodosFlujo_Factura(
                    " where factura_id in (select factura_id from Factura where cliente_id = "
                            + String.valueOf(jTextFieldIdentificacionClienteReporte.getText())
                            + ") order by factura_id");
            // {"flujo_id","factura_id","tipo_flujo","fecha","valor"};
            ArrayList<Calendar> fechasFlujos = new ArrayList<>();

            for (int i = 0; i < flujosCliente.size(); i++) {
                String fila[] = new String[4];
                String[] objeto = flujosCliente.get(i);
                fila[0] = objeto[1];
                fila[1] = objeto[2];
                fila[2] = objeto[3];
                fila[3] = objeto[4];

                //Filtrar, mirar las fechas
                String[] partirEspacios = objeto[3].split("\\s");
                //El primer string es la fecha sin hora
                //Ahora esparamos por -
                String[] tomarAgeMesDia = partirEspacios[0].split("-");

                //Realizar filtro
                int ageConsulta = Integer.parseInt(tomarAgeMesDia[0]);
                int mesConsulta = Integer.parseInt(tomarAgeMesDia[1]);
                int diaConsulta = Integer.parseInt(tomarAgeMesDia[2]);

                //Obtenemos dias, mes y ao de la consulta
                //Inicial
                int anioInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.YEAR);
                int mesInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.MONTH) + 1;
                int diaInicial = clienteReporteClienteFechaFinal.getSelectedDate().get(Calendar.DAY_OF_MONTH);
                //Final
                int anioFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.YEAR);
                int mesFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.MONTH) + 1;
                int diaFinal = clienteReporteClienteFechaInicial.getSelectedDate().get(Calendar.DAY_OF_MONTH);

                //Construir fechas
                Calendar fechaDeLaBD = new GregorianCalendar(ageConsulta, mesConsulta, diaConsulta);
                //Set year, month, day)

                Calendar fechaInicialRango = new GregorianCalendar(anioInicial, mesInicial, diaInicial);
                Calendar fechaFinalRango = new GregorianCalendar(anioFinal, mesFinal, diaFinal);

                if (fechaDeLaBD.compareTo(fechaInicialRango) <= 0
                        && fechaDeLaBD.compareTo(fechaFinalRango) >= 0) {
                    fechasFlujos.add(fechaDeLaBD);
                    modeloTabla.addRow(fila);
                }

            }

            if (modeloTabla.getRowCount() > 0) {
                tablaDialogo.setModel(modeloTabla);
                tablaDialogo.getColumn("Factura").setMinWidth(80);
                tablaDialogo.getColumn("Tipo Flujo").setMinWidth(80);
                tablaDialogo.getColumn("Fecha").setMinWidth(90);
                tablaDialogo.getColumn("Valor").setMinWidth(80);
                tablaDialogo.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                JScrollPane scroll = new JScrollPane(tablaDialogo);
                scroll.setPreferredSize(new Dimension(330, 150));

                c.gridx = 0;
                c.gridy = 1;
                c.gridwidth = 1;
                c.insets = new Insets(0, 0, 0, 0);
                panelDialogo.add(scroll, c);

                TimeSeries localTimeSeries = new TimeSeries("Compras del cliente en el periodo");

                Map listaAbonos = new HashMap();

                for (int i = 0; i < modeloTabla.getRowCount(); i++) {
                    listaIDFlujos.add(Integer.parseInt(flujosCliente.get(i)[0]));

                    if (modeloTabla.getValueAt(i, 1).equals("abono")) {
                        Calendar fechaFlujo = fechasFlujos.get(i);
                        double valor = Double.parseDouble(String.valueOf(modeloTabla.getValueAt(i, 3)));

                        int anoDato = fechaFlujo.get(Calendar.YEAR);
                        int mesDato = fechaFlujo.get(Calendar.MONTH) + 1;
                        int diaDato = fechaFlujo.get(Calendar.DAY_OF_MONTH);
                        Day FechaDato = new Day(diaDato, mesDato, anoDato);

                        if (listaAbonos.get(FechaDato) != null) {
                            double valorAbono = (double) listaAbonos.get(FechaDato);
                            listaAbonos.remove(FechaDato);
                            listaAbonos.put(FechaDato, valorAbono + valor);
                        } else {
                            listaAbonos.put(FechaDato, valor);

                        }

                    }

                }
                Double maximo = 0.0;
                Iterator iterator = listaAbonos.keySet().iterator();
                while (iterator.hasNext()) {
                    Day key = (Day) iterator.next();
                    Double value = (double) listaAbonos.get(key);
                    maximo = Math.max(maximo, value);
                    localTimeSeries.add(key, value);
                }

                //localTimeSeries.add();
                TimeSeriesCollection datos = new TimeSeriesCollection(localTimeSeries);

                JFreeChart chart = ChartFactory.createTimeSeriesChart("Compras del cliente en el periodo", // Title
                        "Tiempo", // x-axis Label
                        "Total ($)", // y-axis Label
                        datos, // Dataset
                        true, // Show Legend
                        true, // Use tooltips
                        false // Configure chart to generate URLs?
                );
                /*Altering the graph */
                XYPlot plot = (XYPlot) chart.getPlot();
                plot.setAxisOffset(new RectangleInsets(5.0, 10.0, 10.0, 5.0));
                plot.setDomainCrosshairVisible(true);
                plot.setRangeCrosshairVisible(true);

                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
                renderer.setBaseShapesVisible(true);
                renderer.setBaseShapesFilled(true);

                NumberAxis numberAxis = (NumberAxis) plot.getRangeAxis();
                numberAxis.setRange(new Range(0, maximo * 1.2));
                Font font = new Font("Dialog", Font.PLAIN, 9);
                numberAxis.setTickLabelFont(font);
                numberAxis.setLabelFont(font);

                DateAxis axis = (DateAxis) plot.getDomainAxis();
                axis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yyyy"));
                axis.setAutoTickUnitSelection(false);
                axis.setVerticalTickLabels(true);

                axis.setTickLabelFont(font);
                axis.setLabelFont(font);

                LegendTitle leyendaChart = chart.getLegend();
                leyendaChart.setItemFont(font);

                Font fontTitulo = new Font("Dialog", Font.BOLD, 12);
                TextTitle tituloChart = chart.getTitle();
                tituloChart.setFont(fontTitulo);

                ChartPanel CP = new ChartPanel(chart);
                Dimension D = new Dimension(330, 300);
                CP.setPreferredSize(D);
                CP.setVisible(true);
                c.gridx = 0;
                c.gridy = 2;
                c.gridwidth = 1;
                c.insets = new Insets(10, 0, 0, 0);
                panelDialogo.add(CP, c);

                c.gridx = 0;
                c.gridy = 3;
                c.gridwidth = 1;
                c.anchor = GridBagConstraints.WEST;
                c.insets = new Insets(10, 30, 0, 0);

                JButton botonCerrar = new JButton("Cerrar");
                botonCerrar.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        dialogoEditar.dispose();
                    }
                });
                panelDialogo.add(botonCerrar, c);

                JButton botonGenerarPDF = new JButton("Guardar archivo");
                botonGenerarPDF.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente();
                        reporteFlujosCliente.guardarDocumentoDialogo(dialogoEditar, listaIDFlujos,
                                Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()),
                                clienteReporteClienteFechaInicial.getSelectedDate(),
                                clienteReporteClienteFechaFinal.getSelectedDate());

                    }
                });
                c.insets = new Insets(10, 100, 0, 0);

                panelDialogo.add(botonGenerarPDF, c);

                JButton botonImprimir = new JButton("Imprimir");
                botonImprimir.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ReporteFlujosCliente reporteFlujosCliente = new ReporteFlujosCliente();
                        reporteFlujosCliente.imprimirFlujo(listaIDFlujos,
                                Integer.parseInt(jTextFieldIdentificacionClienteReporte.getText()),
                                clienteReporteClienteFechaInicial.getSelectedDate(),
                                clienteReporteClienteFechaFinal.getSelectedDate());

                    }
                });
                c.insets = new Insets(10, 230, 0, 0);

                panelDialogo.add(botonImprimir, c);
                dialogoEditar.add(panelDialogo);

                dialogoEditar.setVisible(true);

            } else {
                JOptionPane.showMessageDialog(this,
                        "El cliente no registra movimientos en el rango de fechas seleccionado");
            }

        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Debe seleccionar un da inicial y final de fechas");
    }

}

From source file:com.smhdemo.common.report.generate.factory.ChartFactory.java

public byte[] export(Chart report, Map<String, String> pageParams) throws Exception {
    if (report == null) {
        return null;
    }//from ww w  .  j  ava 2 s  . co m
    DefaultCategoryDataset dataset = buildDataset(report, pageParams);
    java.awt.Font titleFont = new java.awt.Font(report.getFontName(), report.getFontStyle(),
            report.getFontSize());
    String chartTitle = report.getChartTitle();
    chartTitle = replaceParam(pageParams, report.getParameters(), chartTitle, false);
    String horizAxisLabel = report.getHorizAxisLabel();
    horizAxisLabel = replaceParam(pageParams, report.getParameters(), horizAxisLabel, false);
    String vertAxisLabel = report.getVertAxisLabel();
    vertAxisLabel = replaceParam(pageParams, report.getParameters(), vertAxisLabel, false);
    Boolean showLegend = report.getShowLegend();
    Boolean showTooltips = report.getShowTooltips();
    Boolean drillThroughEnabled = false;
    Chart.Type chartType = report.getType();

    CategoryURLGenerator urlGenerator = null;

    JFreeChart chart = null;
    switch (chartType) {
    case VERTBAR:
        chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case VERTBAR3D:
        chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZBAR:
        chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case HORIZBAR3D:
        chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDVERTBAR:
        chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDVERTBAR3D:
        chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDHORIZBAR:
        chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case STACKEDHORIZBAR3D:
        chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case VERTLINE:
        chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZLINE:
        chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case VERTAREA:
        chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZAREA:
        chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case VERTSTACKEDAREA:
        chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case HORIZSTACKEDAREA:
        chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case PIEBYCOLUMN:
        chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    case PIEBYROW:
        chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    case PIEBYCOLUMN3D:
        chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                showLegend, showTooltips, drillThroughEnabled, null);

        break;
    case PIEBYROW3D:
        chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    default:
        throw new BaseException("", "");
    }
    try {
        Integer bgColorR = report.getBgColorR();
        Integer bgColorG = report.getBgColorG();
        Integer bgColorB = report.getBgColorB();
        chart.setBackgroundPaint(new java.awt.Color(bgColorR, bgColorG, bgColorB));

        String axisFontName = report.getAxisFontName();
        Integer axisFontStyle = report.getAxisFontStyle();
        Integer axisFontSize = report.getAxisFontSize();
        java.awt.Font axisFont = new java.awt.Font(axisFontName, axisFontStyle, axisFontSize);

        String axisTickFontName = report.getAxisTickFontName();
        Integer axisTickFontStyle = report.getAxisTickFontStyle();
        Integer axisTickFontSize = report.getAxisTickFontSize();
        java.awt.Font axisTickFont = new java.awt.Font(axisTickFontName, axisTickFontStyle, axisTickFontSize);

        String legendFontName = report.getLegendFontName();
        Integer legendFontStyle = report.getLegendFontStyle();
        Integer legendFontSize = report.getLegendFontSize();
        java.awt.Font legendFont = new java.awt.Font(legendFontName, legendFontStyle, legendFontSize);
        Integer tickLabelRotate = report.getTickLabelRotate();

        String dataFontName = report.getDataFontName();
        Integer dataFontStyle = report.getDataFontStyle();
        Integer dataFontSize = report.getDataFontSize();
        java.awt.Font dataFont = new java.awt.Font(dataFontName, dataFontStyle, dataFontSize);

        Plot plot = chart.getPlot();
        if (!(plot instanceof MultiplePiePlot)) {
            CategoryPlot categoryPlot = chart.getCategoryPlot();
            CategoryItemRenderer renderer = categoryPlot.getRenderer();
            renderer.setBaseItemLabelGenerator(new LabelGenerator(0.0));
            renderer.setBaseItemLabelFont(dataFont);
            renderer.setBaseItemLabelsVisible(true);
            if (chartType == Chart.Type.VERTLINE || chartType == Chart.Type.HORIZLINE) {
                LineAndShapeRenderer lineRenderer = (LineAndShapeRenderer) categoryPlot.getRenderer();
                lineRenderer.setBaseShapesVisible(true);
                lineRenderer.setDrawOutlines(true);
                lineRenderer.setUseFillPaint(true);
            }
        }

        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.setLabelFont(axisFont);
            piePlot.setDirection(org.jfree.util.Rotation.CLOCKWISE);
            piePlot.setForegroundAlpha(0.5f);
            piePlot.setNoDataMessage("?");
        } else if (plot instanceof PiePlot) {
            PiePlot piePlot = (PiePlot) plot;
            piePlot.setLabelFont(axisFont);
        }
        LegendTitle legend = (LegendTitle) chart.getLegend();
        if (legend != null) {
            legend.setItemFont(legendFont);
            RectangleEdge legendRectEdge = RectangleEdge.BOTTOM;
            Integer legendPosition = report.getLegendPosition();
            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);
        }
    } catch (Exception e) {
        logger.error("Chart Export Exception", e);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ChartUtilities.writeChartAsPNG(out, chart, report.getChartWidth(), report.getChartHeight());
    return out.toByteArray();
}

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.
 *//*from ww  w . j av  a  2s  .  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:com.ewcms.plugin.report.generate.factory.ChartFactory.java

public byte[] export(ChartReport report, Map<String, String> pageParams) throws Exception {
    if (report == null) {
        return null;
    }//ww  w  . j a va 2s  .  c o m
    DefaultCategoryDataset dataset = buildDataset(report, pageParams);
    java.awt.Font titleFont = new java.awt.Font(report.getFontName(), report.getFontStyle(),
            report.getFontSize());
    String chartTitle = report.getChartTitle();
    chartTitle = replaceParam(pageParams, report.getParameters(), chartTitle, false);
    String horizAxisLabel = report.getHorizAxisLabel();
    horizAxisLabel = replaceParam(pageParams, report.getParameters(), horizAxisLabel, false);
    String vertAxisLabel = report.getVertAxisLabel();
    vertAxisLabel = replaceParam(pageParams, report.getParameters(), vertAxisLabel, false);
    Boolean showLegend = report.getShowLegend();
    Boolean showTooltips = report.getShowTooltips();
    Boolean drillThroughEnabled = false;
    ChartReport.Type chartType = report.getType();

    CategoryURLGenerator urlGenerator = null;

    JFreeChart chart = null;
    switch (chartType) {
    case VERTBAR:
        chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case VERTBAR3D:
        chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZBAR:
        chart = ChartGenerationService.createBarChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case HORIZBAR3D:
        chart = ChartGenerationService.createBarChart3D(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDVERTBAR:
        chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDVERTBAR3D:
        chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case STACKEDHORIZBAR:
        chart = ChartGenerationService.createStackedBarChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case STACKEDHORIZBAR3D:
        chart = ChartGenerationService.createStackedBarChart3D(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case VERTLINE:
        chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZLINE:
        chart = ChartGenerationService.createLineChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case VERTAREA:
        chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled, urlGenerator);
        break;
    case HORIZAREA:
        chart = ChartGenerationService.createAreaChart(chartTitle, titleFont, horizAxisLabel, vertAxisLabel,
                dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case VERTSTACKEDAREA:
        chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.VERTICAL, showLegend, showTooltips, drillThroughEnabled,
                urlGenerator);
        break;
    case HORIZSTACKEDAREA:
        chart = ChartGenerationService.createStackedAreaChart(chartTitle, titleFont, horizAxisLabel,
                vertAxisLabel, dataset, PlotOrientation.HORIZONTAL, showLegend, showTooltips,
                drillThroughEnabled, urlGenerator);
        break;
    case PIEBYCOLUMN:
        chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    case PIEBYROW:
        chart = ChartGenerationService.createPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    case PIEBYCOLUMN3D:
        chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_COLUMN,
                showLegend, showTooltips, drillThroughEnabled, null);

        break;
    case PIEBYROW3D:
        chart = ChartGenerationService.create3DPieChart(chartTitle, titleFont, dataset, TableOrder.BY_ROW,
                showLegend, showTooltips, drillThroughEnabled, null);
        break;
    default:
        throw new BaseException("", "");
    }
    try {
        Integer bgColorR = report.getBgColorR();
        Integer bgColorG = report.getBgColorG();
        Integer bgColorB = report.getBgColorB();
        chart.setBackgroundPaint(new java.awt.Color(bgColorR, bgColorG, bgColorB));

        String axisFontName = report.getAxisFontName();
        Integer axisFontStyle = report.getAxisFontStyle();
        Integer axisFontSize = report.getAxisFontSize();
        java.awt.Font axisFont = new java.awt.Font(axisFontName, axisFontStyle, axisFontSize);

        String axisTickFontName = report.getAxisTickFontName();
        Integer axisTickFontStyle = report.getAxisTickFontStyle();
        Integer axisTickFontSize = report.getAxisTickFontSize();
        java.awt.Font axisTickFont = new java.awt.Font(axisTickFontName, axisTickFontStyle, axisTickFontSize);

        String legendFontName = report.getLegendFontName();
        Integer legendFontStyle = report.getLegendFontStyle();
        Integer legendFontSize = report.getLegendFontSize();
        java.awt.Font legendFont = new java.awt.Font(legendFontName, legendFontStyle, legendFontSize);
        Integer tickLabelRotate = report.getTickLabelRotate();

        String dataFontName = report.getDataFontName();
        Integer dataFontStyle = report.getDataFontStyle();
        Integer dataFontSize = report.getDataFontSize();
        java.awt.Font dataFont = new java.awt.Font(dataFontName, dataFontStyle, dataFontSize);

        Plot plot = chart.getPlot();
        if (!(plot instanceof MultiplePiePlot)) {
            CategoryPlot categoryPlot = chart.getCategoryPlot();
            CategoryItemRenderer renderer = categoryPlot.getRenderer();
            renderer.setBaseItemLabelGenerator(new LabelGenerator(0.0));
            renderer.setBaseItemLabelFont(dataFont);
            renderer.setBaseItemLabelsVisible(true);
            if (chartType == ChartReport.Type.VERTLINE || chartType == ChartReport.Type.HORIZLINE) {
                LineAndShapeRenderer lineRenderer = (LineAndShapeRenderer) categoryPlot.getRenderer();
                lineRenderer.setBaseShapesVisible(true);
                lineRenderer.setDrawOutlines(true);
                lineRenderer.setUseFillPaint(true);
            }
        }

        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.setLabelFont(axisFont);
            piePlot.setDirection(org.jfree.util.Rotation.CLOCKWISE);
            piePlot.setForegroundAlpha(0.5f);
            piePlot.setNoDataMessage("?");
        } else if (plot instanceof PiePlot) {
            PiePlot piePlot = (PiePlot) plot;
            piePlot.setLabelFont(axisFont);
        }
        LegendTitle legend = (LegendTitle) chart.getLegend();
        if (legend != null) {
            legend.setItemFont(legendFont);
            RectangleEdge legendRectEdge = RectangleEdge.BOTTOM;
            Integer legendPosition = report.getLegendPosition();
            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);
        }
    } catch (Exception e) {
        logger.error("Chart Export Exception", e);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ChartUtilities.writeChartAsPNG(out, chart, report.getChartWidth(), report.getChartHeight());
    return out.toByteArray();
}