Example usage for org.jfree.chart JFreeChart getCategoryPlot

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

Introduction

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

Prototype

public CategoryPlot getCategoryPlot() 

Source Link

Document

Returns the plot cast as a CategoryPlot .

Usage

From source file:uk.ac.ed.epcc.webapp.charts.jfreechart.JFreeBarTimeChartData.java

@Override
public JFreeChart getJFreeChart() {
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    double counts[] = ds.getCounts();
    String legends[] = ds.getLegends();
    int max_len = 0;
    for (int i = 0; i < ds.getNumSets(); i++) {
        if (legends != null && legends.length > i) {
            dataset.addValue(new Double(counts[i]), "Series-1", legends[i]);
            int leg_len = legends[i].length();
            if (leg_len > max_len) {
                max_len = leg_len;/*from w  w w  .  j  a  v  a2 s  . co m*/
            }
            //System.out.println(legends[i] + counts[i]);
        } else {
            dataset.addValue(new Double(counts[i]), "Series-1", Integer.toString(i));
        }
    }
    CategoryDataset data = dataset;

    JFreeChart chart = ChartFactory.createBarChart(title, null, quantity, data, PlotOrientation.VERTICAL, false, // include legends
            false, // tooltips
            false // urls
    );

    CategoryPlot categoryPlot = chart.getCategoryPlot();
    CategoryAxis axis = categoryPlot.getDomainAxis();
    if (max_len > 8 || ds.getNumSets() > 16 || (max_len * ds.getNumSets()) > 50) {
        axis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
    }
    Font tickLabelFont = axis.getTickLabelFont();
    if (ds.getNumSets() > 24) {
        axis.setTickLabelFont(tickLabelFont.deriveFont(tickLabelFont.getSize() - 2.0F));
    }
    Font labelFont = axis.getLabelFont();
    axis.setMaximumCategoryLabelLines(3);
    //axis.setLabelFont(labelFont.d);
    // axis.setLabel("Pingu"); This works so we can modify

    return chart;

}

From source file:graficos.GenerarGraficoFinanciero.java

public void crear() {
    try {/*from  ww w. ja v a2  s. c  o m*/
        Dba db = new Dba(pathdb);
        db.conectar();
        String sql = "select IdCategoria, Nombre from Categoria";
        db.prepare(sql);
        db.query.execute();
        ResultSet rs = db.query.getResultSet();
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        String fechai = periodo.substring(0, 10) + " 00:00:00";
        String fechaf = periodo.substring(13, 23) + " 00:00:00";
        while (rs.next()) {
            String sql1 = "select Monto from PagoCliente join FichaCliente on PagoCliente.IdFichaCliente=FichaCliente.IdFichaCliente"
                    + " join Reservacion  on Reservacion.IdReservacion=FichaCliente.IdReservacion join Habitacion on Reservacion.IdHabitacion="
                    + "Habitacion.IdHabitacion  where Habitacion.IdCategoria=" + rs.getInt(1)
                    + " and FichaCliente.FechaSalida>='" + fechai + "' and" + " FichaCliente.FechaSalida<='"
                    + fechaf + "'";
            db.prepare(sql1);
            db.query.execute();
            ResultSet rs1 = db.query.getResultSet();
            Double monto = 0.0;

            while (rs1.next()) {
                monto += rs1.getDouble(1);
            }
            dataset.setValue(monto, "Ingresos", rs.getString(2));
        }

        JFreeChart chart = ChartFactory.createBarChart3D(
                "Comparacin de Ingresos por Categora\nPeriodo:" + periodo, "Categora", "Ingresos",
                dataset, PlotOrientation.VERTICAL, false, true, false);
        CategoryPlot p = chart.getCategoryPlot(); // Get the Plot object for a bar graph
        p.setBackgroundPaint(Color.black);

        try {
            ChartUtilities.saveChartAsJPEG(new File(path), chart, 500, 300);
        } catch (Exception ee) {
            System.err.println(ee.toString());
            System.err.println("Problem occurred creating chart.");
        }

        db.desconectar();
    } catch (Exception e) {

    }

}

From source file:org.squale.squaleweb.util.graph.BarMaker.java

/**
 * @return le diagramme JFreeChart// www. j  a v a 2  s .co  m
 */
protected JFreeChart getChart() {
    JFreeChart retChart = super.getChart();
    if (null == retChart) {
        retChart = ChartFactory.createBarChart3D(mTitle, mXLabel, mYLabel, mDataSet, PlotOrientation.VERTICAL,
                false, false, false);

        CategoryPlot plot = retChart.getCategoryPlot();

        // Les valeurs sont des entiers
        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

        // On effectue une rotation de 90 pour afficher le titre des abscisses  la verticale
        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(
                CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 2.0));
        super.setChart(retChart);
    }
    return retChart;
}

From source file:edu.emory.library.tast.database.graphs.GraphTypeBar.java

public JFreeChart createChart(Object[] data) {

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    JFreeChart chart = ChartFactory.createBarChart(null, getSelectedIndependentVariable().getLabel(),
            TastResource.getText("components_charts_barvalue"), dataset, PlotOrientation.VERTICAL, true, true,
            false);//from   ww w .j a  v a  2 s  . c o m

    CategoryPlot plot = chart.getCategoryPlot();
    plot.getDomainAxis().setMaximumCategoryLabelLines(5);
    plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);
    chart.setBackgroundPaint(Color.white);

    Format formatter = getSelectedIndependentVariable().getFormat();

    List allDataSeries = getDataSeries();
    for (int j = 0; j < allDataSeries.size(); j++) {

        DataSeries dataSearies = (DataSeries) allDataSeries.get(j);
        String dataSeriesLabel = dataSearies.formatForDisplay();

        for (int i = 0; i < data.length; i++) {
            Object[] row = (Object[]) data[i];

            String cat = formatter == null ? row[0].toString() : formatter.format(row[0]);

            dataset.addValue((Number) row[j + 1], dataSeriesLabel, cat);
        }
    }

    LegendItemCollection legendItems = chart.getPlot().getLegendItems();
    for (int i = 0; i < legendItems.getItemCount(); i++) {
        LegendItem legendItem = legendItems.get(i);
        DataSeries dataSearies = (DataSeries) allDataSeries.get(i);
        if (legendItem.getFillPaint() instanceof Color) {
            dataSearies.setColor(((Color) legendItem.getFillPaint()));
        }
    }

    return chart;

}

From source file:it.eng.spagobi.engines.kpi.bo.charttypes.dialcharts.BulletGraph.java

public JFreeChart createChart() {

    logger.debug("IN");
    Number value = null;/*w ww . ja v  a 2 s.  c om*/

    if (dataset == null) {
        logger.debug("The dataset to be represented is null");
        value = new Double(0);
    } else {
        value = dataset.getValue();
    }

    DefaultCategoryDataset datasetC = new DefaultCategoryDataset();
    datasetC.addValue(value, "", "");

    // customize a bar chart 
    JFreeChart chart = ChartFactory.createBarChart(null, null, null, datasetC, PlotOrientation.HORIZONTAL,
            false, false, false);
    chart.setBorderVisible(false);

    CategoryPlot plot = chart.getCategoryPlot();
    plot.setOutlineVisible(true);
    plot.setOutlinePaint(Color.BLACK);

    plot.setInsets(new RectangleInsets(0.0, 0.0, 0.0, 0.0));
    plot.setBackgroundPaint(null);
    plot.setDomainGridlinesVisible(false);
    plot.setRangeGridlinesVisible(false);
    plot.setRangeCrosshairVisible(false);
    plot.setAnchorValue(value.doubleValue());

    // add the target marker 
    if (target != null) {
        ValueMarker marker = new ValueMarker(target.doubleValue(), Color.BLACK, new BasicStroke(2.0f));
        plot.addRangeMarker(marker, Layer.FOREGROUND);
    }

    //sets different marks
    for (Iterator iterator = intervals.iterator(); iterator.hasNext();) {
        KpiInterval interval = (KpiInterval) iterator.next();
        // add the marks 
        IntervalMarker marker = new IntervalMarker(interval.getMin(), interval.getMax(), interval.getColor());
        plot.addRangeMarker(marker, Layer.BACKGROUND);
        logger.debug("Added new interval to the plot");
    }

    // customize axes 
    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setVisible(false);

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setVisible(show_axis);
    rangeAxis.setLabelFont(new Font("Arial", Font.PLAIN, 4));
    // calculate the upper limit 
    //double upperBound = target * upperFactor; 
    rangeAxis.setRange(new Range(lower, upper));
    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);

    // customize renderer 
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setMaximumBarWidth(0.18);
    renderer.setSeriesPaint(0, Color.BLACK);
    /*BasicStroke d = new BasicStroke(3f,BasicStroke.CAP_ROUND ,BasicStroke.JOIN_ROUND);
    renderer.setSeriesOutlineStroke(0, d);
    renderer.setSeriesStroke(0, d);
            
    renderer.setStroke(d);*/

    return chart;
}

From source file:net.sf.jooreports.web.samples.SalesReportGenerator.java

private RenderedImage createChart(Object model) {
    List lines = (List) ((Map) model).get("lines");
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (Iterator it = lines.iterator(); it.hasNext();) {
        ReportLine line = (ReportLine) it.next();
        dataset.addValue(line.getValue(), "sales", line.getMonth());
    }//from  ww w.  j  a v  a  2s.com
    JFreeChart chart = ChartFactory.createBarChart("Monthly Sales", "Month", "Sales", dataset,
            PlotOrientation.VERTICAL, false, false, false);
    chart.setTitle((String) null);
    chart.setBackgroundPaint(Color.white);
    CategoryPlot plot = chart.getCategoryPlot();
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    GradientPaint paint = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, new Color(0, 0, 64));
    renderer.setSeriesPaint(0, paint);
    BufferedImage image = chart.createBufferedImage(400, 300);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        ImageIO.write(image, "png", outputStream);
    } catch (IOException ioException) {
        throw new RuntimeException("should never happen: " + ioException.getMessage());
    }
    return image;
}

From source file:Visuals.BarChart.java

public ChartPanel drawBarChart() {
    DefaultCategoryDataset bardataset = new DefaultCategoryDataset();
    bardataset.addValue(new Double(low), "Low (" + low + ")", lowValue);
    bardataset.addValue(new Double(medium), "Medium (" + medium + ")", mediumValue);
    bardataset.addValue(new Double(high), "High (" + high + ")", highValue);
    bardataset.addValue(new Double(critical), "Critical (" + critical + ")", criticalValue);

    JFreeChart barchart = ChartFactory.createBarChart(title, // Title  
            riskCategory, riskCountTitle, bardataset // Dataset   
    );//w  ww  . j a v a 2s  . co m

    final CategoryPlot plot = barchart.getCategoryPlot();
    CategoryItemRenderer renderer = new CustomRenderer();
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    renderer.setBaseItemLabelGenerator(
            new StandardCategoryItemLabelGenerator(riskCountTitle, NumberFormat.getInstance()));

    DecimalFormat df = new DecimalFormat("##");
    renderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator("{2}", df));
    Font m1Font;
    m1Font = new Font("Cambria", Font.BOLD, 16);
    renderer.setItemLabelFont(m1Font);
    renderer.setItemLabelPaint(null);

    //barchart.removeLegend();
    plot.setRenderer(renderer);
    //renderer.setPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE5, TextAnchor.CENTER));
    //renderer.setItemLabelsVisible(true);
    barchart.getCategoryPlot().setRenderer(renderer);

    LegendItemCollection chartLegend = new LegendItemCollection();
    Shape shape = new Rectangle(10, 10);
    chartLegend.add(new LegendItem("Low (" + low + ")", null, null, null, shape, new Color(230, 219, 27)));
    chartLegend
            .add(new LegendItem("Medium (" + medium + ")", null, null, null, shape, new Color(85, 144, 176)));
    chartLegend.add(new LegendItem("High (" + high + ")", null, null, null, shape, new Color(230, 90, 27)));
    chartLegend.add(
            new LegendItem("Critical (" + critical + ")", null, null, null, shape, new Color(230, 27, 27)));
    plot.setFixedLegendItems(chartLegend);
    plot.setBackgroundPaint(new Color(210, 234, 243));
    ChartPanel chartPanel = new ChartPanel(barchart);
    return chartPanel;
}

From source file:datavis.BarGraph.java

public JFreeChart getChartPanel() {
    JFreeChart chart = ChartFactory.createBarChart(getBarGraphName(), getIntervalTypeName(),
            getNumberTypeName(), getBarGraph(), PlotOrientation.VERTICAL, true, true, false);
    chart.setBackgroundPaint(Color.white);

    final CategoryPlot plot = chart.getCategoryPlot();
    plot.setBackgroundPaint(Color.darkGray);
    plot.setDomainGridlinePaint(new Color(240, 180, 180));
    plot.setRangeGridlinePaint(new Color(240, 180, 180));

    final BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setBarPainter(new StandardBarPainter());

    final GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, new Color(170, 240, 240), 0.0f, 0.0f,
            new Color(170, 240, 240));

    renderer.setSeriesPaint(0, gp0);/* w w w . j  a  va2s  .  c o  m*/

    final CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));

    return chart;
}

From source file:GUI.GraficaView.java

private void init() {
    ArrayList<OperacionesDiarias> aux = operario.getArrayOperacionesDiarias();
    Collections.sort(aux);//w ww . j a  v a2 s  .c  om

    panel = new JPanel();
    getContentPane().add(panel);
    // Fuente de Datos
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (OperacionesDiarias op : aux) {
        if (op.getListaOperaciones().size() > 0) {
            dataset.setValue(op.getPorcentaje(), operario.getNombre(), op.getFecha());
        }

    }

    // Creando el Grafico
    JFreeChart chart = ChartFactory.createBarChart3D("Rendimiento", "Dia", "Porcentaje %", dataset,
            PlotOrientation.VERTICAL, true, true, false);
    chart.setBackgroundPaint(Color.LIGHT_GRAY);
    chart.getTitle().setPaint(Color.black);
    CategoryPlot p = chart.getCategoryPlot();
    p.setRangeGridlinePaint(Color.red);

    // Mostrar Grafico
    ChartPanel chartPanel = new ChartPanel(chart);
    panel.add(chartPanel);
    repaint();
}

From source file:Reportes.BarChart.java

public ChartPanel reporteAportesVentas(DefaultCategoryDataset data) {
    JFreeChart chart = ChartFactory.createBarChart("Reporte de aporte por sede", "Sedes", "Aporte", data,
            PlotOrientation.VERTICAL, true, true, true);

    CategoryPlot categoryP = chart.getCategoryPlot();
    BarRenderer renderer = (BarRenderer) categoryP.getRenderer();
    renderer.setMaximumBarWidth(0.35);// www .  j a v  a2 s.c o m
    Color color = new Color(67, 165, 208);
    renderer.setSeriesPaint(0, color);

    ChartPanel panel = new ChartPanel(chart, true, true, true, false, false);
    panel.setSize(ancho, alto);

    return panel;
}