Example usage for org.jfree.chart ChartFactory createXYBarChart

List of usage examples for org.jfree.chart ChartFactory createXYBarChart

Introduction

In this page you can find the example usage for org.jfree.chart ChartFactory createXYBarChart.

Prototype

public static JFreeChart createXYBarChart(String title, String xAxisLabel, boolean dateAxis, String yAxisLabel,
        IntervalXYDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips,
        boolean urls) 

Source Link

Document

Creates and returns a default instance of an XY bar chart.

Usage

From source file:org.openscience.cdk.applications.taverna.basicutilities.ChartTool.java

/**
 * Creates a XY bar chart./*from  w  w  w  .ja  v  a2s .  c o  m*/
 * 
 * @param title
 * @param categoryAxisLabel
 * @param valueAxisLabel
 * @param dataset
 * @param includeZero
 * @param shadow
 * @return
 */
public JFreeChart createXYBarChart(String title, String categoryAxisLabel, String valueAxisLabel,
        IntervalXYDataset dataset, boolean includeZero, boolean shadow) {
    JFreeChart chart = ChartFactory.createXYBarChart(title, categoryAxisLabel, false, valueAxisLabel, dataset,
            this.orientation, this.drawLegend, false, false);
    // set the background color for the chart...
    chart.setBackgroundPaint(Color.white);
    chart.setAntiAlias(true);
    XYPlot plot = chart.getXYPlot();
    ValueAxis domainAxis = plot.getDomainAxis();
    domainAxis.setLowerMargin(0.025);
    domainAxis.setUpperMargin(0.025);
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setAutoRangeIncludesZero(includeZero);
    XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);
    renderer.setShadowVisible(shadow);
    renderer.setSeriesPaint(0, Color.blue);
    renderer.setSeriesPaint(1, Color.red);
    renderer.setSeriesPaint(2, Color.green);
    renderer.setSeriesPaint(3, Color.darkGray);
    renderer.setSeriesPaint(4, Color.yellow);
    return chart;
}

From source file:edu.ucla.stat.SOCR.chart.SuperIntervalXYChart_Time.java

/**
 * Creates a chart./*from  w ww.j  ava  2 s.co  m*/
 * 
 * @param dataset  the dataset.
 * 
 * @return a chart.
 */
protected JFreeChart createChart(IntervalXYDataset dataset) {
    JFreeChart chart = ChartFactory.createXYBarChart(chartTitle, // chart title
            domainLabel, // domain axis label
            true, rangeLabel, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, !legendPanelOn, // include legend
            true, false);

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
    XYPlot plot = chart.getXYPlot();
    plot.setRenderer(new ClusteredXYBarRenderer());
    // OPTIONAL CUSTOMISATION COMPLETED.
    return chart;
}

From source file:de.xirp.chart.ChartManager.java

/**
 * Returns a bar chart. The chart is generated from the given
 * {@link de.xirp.db.Record} and key array. The
 * record is evaluated from the given start to the given stop
 * time, or is evaluated completely if the flag
 * <code>origTime</code> is set to <code>true</code>.
 * /*from   www  .  ja v  a  2 s  . co m*/
 * @param record
 *            The record containing the data.
 * @param keys
 *            The keys to use.
 * @param start
 *            The start time.
 * @param stop
 *            The stop time.
 * @param origTime
 *            A flag indicating if the original time should be
 *            used.
 * @return A bar chart.
 * @see org.jfree.chart.JFreeChart
 * @see de.xirp.db.Record
 */
private static JFreeChart createBarChart(Record record, String[] keys, long start, long stop,
        boolean origTime) {

    String chartTitle = createChartTitle(record, keys);

    List<Observed> all = new ArrayList<Observed>();
    TimeSeriesCollection dataset = createTimeSeriesAndFillAllObservedList(all, record, keys, origTime, start,
            stop);

    JFreeChart chart = ChartFactory.createXYBarChart(chartTitle, I18n.getString("ChartManager.text.time"), //$NON-NLS-1$
            true, I18n.getString("ChartManager.text.value"), dataset, PlotOrientation.VERTICAL, true, true, //$NON-NLS-1$
            false);

    XYPlot plot = (XYPlot) chart.getPlot();
    setXYPlot(plot, new Date(record.getStart()));

    exportAutomatically(all, chart);

    return chart;
}

From source file:desmoj.extensions.visualization2d.engine.modelGrafic.StatisticGrafic.java

/**
 * Build content for animationType StatisticGrafic.ANIMATION_Histogram
 * @return//from  w  w w.java 2s  . c  om
 * @throws ModelException
 */
private JPanel buildHistogramPanel() throws ModelException {
    XIntervalSeriesCollection dataset = new XIntervalSeriesCollection();
    dataset.addSeries(this.statistic.getHistogram());
    this.chart = ChartFactory.createXYBarChart(null, "Observation", false, "Count", dataset,
            PlotOrientation.VERTICAL, false, true, false);
    this.chart.setBackgroundPaint(Grafic.COLOR_BACKGROUND);
    XYPlot plot = this.chart.getXYPlot();
    plot.setBackgroundPaint(StatisticGrafic.DIAGRAM_BACKGROUND);
    plot.setDomainGridlinePaint(StatisticGrafic.DIAGRAM_GRID);
    plot.setRangeGridlinePaint(StatisticGrafic.DIAGRAM_GRID);
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    ValueAxis rangeAxis = (ValueAxis) plot.getRangeAxis();
    rangeAxis.setLabelFont(Grafic.FONT_DEFAULT);
    ValueAxis domainAxis = plot.getDomainAxis();
    domainAxis.setLabelFont(Grafic.FONT_DEFAULT);
    domainAxis.setAutoRange(true);

    XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();
    renderer.setShadowVisible(false);
    renderer.setBarPainter(new StandardXYBarPainter());
    renderer.setDrawBarOutline(true);
    renderer.setSeriesPaint(0, StatisticGrafic.DIAGRAM_FORGROUND);
    renderer.setSeriesOutlinePaint(0, StatisticGrafic.DIAGRAM_BORDER);
    renderer.setSeriesOutlineStroke(0, new BasicStroke(1.0f));

    this.buildHistogramAxisFormat(plot, "Observations");
    JPanel out = new ChartPanel(chart);
    out.setPreferredSize(new Dimension(350, 200));
    return out;
}

From source file:de.fau.amos.ChartRenderer.java

/**
 * Creates Chart with Bars (JFreeChart object) from TimeSeriesCollection. Is used when granularity is set to days, months or years.
 * Adjusts display of the chart, not the values itself.
 * /*  w w  w  . ja  va2 s  . c  o  m*/
 * @param collection TimeSeriesCollection that should be used as basis of chart.
 * @param timeGranularity Selected granularity. Value is similar to granularity contained in TimeSeriesCollection "collection".
 * @param time first element of time that is displayed. Is used for caption text and axis text.
 * @param unit Unit of displayed values (kWh or kWh/TNF).
 * @return Returns finished JFreeChart object.
 */
private JFreeChart createTimeBarChart(TimeSeriesCollection collection, String timeGranularity, String time,
        String unit) {

    String xAxisLabel = null;

    // Modification of X-Axis Label (depending on the granularity)
    int month;

    String monthString = null;
    switch (timeGranularity) {
    //for Case "0" see method "createTimeLineChart"
    case "1":
        month = Integer.parseInt(time.substring(5, 7));
        monthString = new DateFormatSymbols(Locale.US).getMonths()[month - 1];
        xAxisLabel = "" + monthString + "  " + time.substring(0, 4);
        break;

    case "2":
        xAxisLabel = time.substring(0, 4);
        break;

    case "3":
        xAxisLabel = "Years";
        break;

    default:
        xAxisLabel = "Timespan";
    }

    JFreeChart barChart = ChartFactory.createXYBarChart("Bar Chart", // title
            xAxisLabel, // x-axis label
            true, // date axis?
            //            "Energy Consumption "+("1".equals(unit)?"[kWh]":("2".equals(unit)?"[kWh/TNF]":("3".equals(unit)?"[TNF]":""))),       // y-axis label
            ("1".equals(unit) ? "Energy Consumption [kWh]"
                    : ("2".equals(unit) ? "Energy Consumption [kWh/TNF]"
                            : ("3".equals(unit) ? "Produced Pieces [TNF]" : ""))),
            collection, // data
            PlotOrientation.VERTICAL, // orientation
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );

    //graphical modifications for BarChart
    barChart.setBackgroundPaint(Color.white);
    XYPlot plot = barChart.getXYPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(0, 0, 0, 0));

    //Axis modification: Set Axis X-Value directly below the bars
    DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
    dateAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);

    //Axis modification: Remove Values from x-Axis that belong to former/later time element (Month/Day)
    dateAxis.setLowerMargin(0.01);
    dateAxis.setUpperMargin(0.01);

    //Axis modification: Axis values (depending on timeGranularity)
    if (timeGranularity.equals("1")) {
        dateAxis.setTickUnit(
                new DateTickUnit(DateTickUnitType.DAY, 2, new SimpleDateFormat("  dd.  ", Locale.US)));
    }
    if (timeGranularity.equals("2")) {
        dateAxis.setTickUnit(
                new DateTickUnit(DateTickUnitType.MONTH, 1, new SimpleDateFormat(" MMM ", Locale.US)));
    }
    if (timeGranularity.equals("3")) {
        dateAxis.setTickUnit(
                new DateTickUnit(DateTickUnitType.YEAR, 1, new SimpleDateFormat(" yyyy ", Locale.US)));
    }

    ClusteredXYBarRenderer clusteredxybarrenderer = new ClusteredXYBarRenderer(0.25, false);
    clusteredxybarrenderer.setShadowVisible(false);
    clusteredxybarrenderer.setBarPainter(new StandardXYBarPainter());
    plot.setRenderer(clusteredxybarrenderer);
    return barChart;

}

From source file:edu.ucla.stat.SOCR.chart.SuperHistogramChart.java

/**
 * Creates a chart.//from www  .  ja v a2 s. co  m
 * 
 * @param dataset  the dataset.
 * 
 * @return a chart.
 */
protected JFreeChart createChart(IntervalXYDataset dataset) {
    JFreeChart chart = ChartFactory.createXYBarChart(chartTitle, // chart title
            domainLabel, // domain axis label
            false, rangeLabel, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL,
            // !legendPanelOn,                       // include legend
            false, //no legend
            true, false);

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
    XYPlot plot = chart.getXYPlot();
    plot.setRenderer(new ClusteredXYBarRenderer());

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
    domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    XYItemRenderer renderer = plot.getRenderer();
    renderer.setLegendItemLabelGenerator(new SOCRXYSeriesLabelGenerator());
    // OPTIONAL CUSTOMISATION COMPLETED.
    return chart;
}

From source file:org.jivesoftware.openfire.reporting.graph.GraphEngine.java

/**
 * Generates a Sparkline Bar Graph.//from   w w  w.  j av  a 2  s  . c  o  m
 *
 * @param def the key of the statistic object.
 * @return the generated chart.
 */
public JFreeChart generateSparklineBarGraph(String key, String color, Statistic[] def, long startTime,
        long endTime, int dataPoints) {
    Color backgroundColor = getBackgroundColor();

    IntervalXYDataset dataset = (IntervalXYDataset) populateData(key, def, startTime, endTime, dataPoints);
    JFreeChart chart = ChartFactory.createXYBarChart(null, // chart title
            null, // domain axis label
            true, null, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, false, // include legend
            false, // tooltips?
            false // URLs?
    );

    chart.setBackgroundPaint(backgroundColor);
    chart.setBorderVisible(false);
    chart.setBorderPaint(null);

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setDomainGridlinesVisible(false);
    plot.setDomainCrosshairVisible(false);
    plot.setRangeCrosshairVisible(false);
    plot.setBackgroundPaint(backgroundColor);
    plot.setRangeGridlinesVisible(false);

    GraphDefinition graphDef = GraphDefinition.getDefinition(color);
    Color plotColor = graphDef.getInlineColor(0);
    plot.getRenderer().setSeriesPaint(0, plotColor);
    plot.getRenderer().setBaseItemLabelsVisible(false);
    plot.getRenderer().setBaseOutlinePaint(backgroundColor);
    plot.setOutlineStroke(null);
    plot.setDomainGridlinePaint(null);

    ValueAxis xAxis = chart.getXYPlot().getDomainAxis();

    xAxis.setLabel(null);
    xAxis.setTickLabelsVisible(true);
    xAxis.setTickMarksVisible(true);
    xAxis.setAxisLineVisible(false);
    xAxis.setNegativeArrowVisible(false);
    xAxis.setPositiveArrowVisible(false);
    xAxis.setVisible(false);

    ValueAxis yAxis = chart.getXYPlot().getRangeAxis();
    yAxis.setTickLabelsVisible(false);
    yAxis.setTickMarksVisible(false);
    yAxis.setAxisLineVisible(false);
    yAxis.setNegativeArrowVisible(false);
    yAxis.setPositiveArrowVisible(false);
    yAxis.setVisible(false);

    return chart;
}

From source file:ca.nengo.plot.impl.DefaultPlotter.java

public ChartPanel getBarChart(float[] vector, String title) {
    XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries series = new XYSeries("MSE Error Plot");

    for (int i = 0; i < vector.length; i++) {
        series.add(i, vector[i]);/* w  w  w . j  a v a 2 s.  c o  m*/
    }

    dataset.addSeries(series);

    JFreeChart chart = ChartFactory.createXYBarChart(title, "Origin Dimension", false, "Error", dataset,
            PlotOrientation.VERTICAL, false, false, false);

    chart.getXYPlot().getDomainAxis()
            .setStandardTickUnits(org.jfree.chart.axis.NumberAxis.createIntegerTickUnits());

    return new ChartPanel(chart);
}

From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java

private byte[] generateTimeSeriesChart(String siteId, IntervalXYDataset dataset, int width, int height,
        boolean renderBar, float transparency, boolean itemLabelsVisible, boolean smallFontInDomainAxis,
        String timePeriod, Date firstDate, Date lastDate) {
    JFreeChart chart = null;/*  w ww.j ava  2  s  .com*/
    if (!renderBar) {
        chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, true, false, false);
    } else {
        chart = ChartFactory.createXYBarChart(null, null, true, null, dataset, PlotOrientation.VERTICAL, true,
                false, false);
    }
    XYPlot plot = (XYPlot) chart.getPlot();

    // set transparency
    plot.setForegroundAlpha(transparency);

    // set background
    chart.setBackgroundPaint(parseColor(M_sm.getChartBackgroundColor()));

    // set chart border
    chart.setPadding(new RectangleInsets(10, 5, 5, 5));
    chart.setBorderVisible(true);
    chart.setBorderPaint(parseColor("#cccccc"));

    // set antialias
    chart.setAntiAlias(true);

    // set domain axis font size
    if (smallFontInDomainAxis && !canUseNormalFontSize(width)) {
        plot.getDomainAxis().setTickLabelFont(new Font("SansSerif", Font.PLAIN, 8));
    }

    // configure date display (localized) in domain axis
    Locale locale = msgs.getLocale();
    PeriodAxis periodaxis = new PeriodAxis(null);
    Class timePeriodClass = null;
    if (dataset instanceof TimeSeriesCollection) {
        TimeSeriesCollection tsc = (TimeSeriesCollection) dataset;
        if (tsc.getSeriesCount() > 0) {
            timePeriodClass = tsc.getSeries(0).getTimePeriodClass();
        } else {
            timePeriodClass = org.jfree.data.time.Day.class;
        }
        periodaxis.setAutoRangeTimePeriodClass(timePeriodClass);
    }
    PeriodAxisLabelInfo aperiodaxislabelinfo[] = null;
    if (StatsManager.CHARTTIMESERIES_WEEKDAY.equals(timePeriod)) {
        aperiodaxislabelinfo = new PeriodAxisLabelInfo[2];
        aperiodaxislabelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Day.class,
                new SimpleDateFormat("E", locale));
        aperiodaxislabelinfo[1] = new PeriodAxisLabelInfo(org.jfree.data.time.Day.class,
                new SimpleDateFormat("d", locale));
    } else if (StatsManager.CHARTTIMESERIES_DAY.equals(timePeriod)) {
        aperiodaxislabelinfo = new PeriodAxisLabelInfo[3];
        aperiodaxislabelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Day.class,
                new SimpleDateFormat("d", locale));
        aperiodaxislabelinfo[1] = new PeriodAxisLabelInfo(org.jfree.data.time.Month.class,
                new SimpleDateFormat("MMM", locale));
        aperiodaxislabelinfo[2] = new PeriodAxisLabelInfo(org.jfree.data.time.Year.class,
                new SimpleDateFormat("yyyy", locale));
    } else if (StatsManager.CHARTTIMESERIES_MONTH.equals(timePeriod)) {
        aperiodaxislabelinfo = new PeriodAxisLabelInfo[2];
        aperiodaxislabelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Month.class,
                new SimpleDateFormat("MMM", locale));
        aperiodaxislabelinfo[1] = new PeriodAxisLabelInfo(org.jfree.data.time.Year.class,
                new SimpleDateFormat("yyyy", locale));
    } else if (StatsManager.CHARTTIMESERIES_YEAR.equals(timePeriod)) {
        aperiodaxislabelinfo = new PeriodAxisLabelInfo[1];
        aperiodaxislabelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Year.class,
                new SimpleDateFormat("yyyy", locale));
    }
    periodaxis.setLabelInfo(aperiodaxislabelinfo);
    // date range
    if (firstDate != null || lastDate != null) {
        periodaxis.setAutoRange(false);
        if (firstDate != null) {
            if (StatsManager.CHARTTIMESERIES_MONTH.equals(timePeriod)
                    || StatsManager.CHARTTIMESERIES_YEAR.equals(timePeriod)) {
                periodaxis.setFirst(new org.jfree.data.time.Month(firstDate));
            } else {
                periodaxis.setFirst(new org.jfree.data.time.Day(firstDate));
            }
        }
        if (lastDate != null) {
            if (StatsManager.CHARTTIMESERIES_MONTH.equals(timePeriod)
                    || StatsManager.CHARTTIMESERIES_YEAR.equals(timePeriod)) {
                periodaxis.setLast(new org.jfree.data.time.Month(lastDate));
            } else {
                periodaxis.setLast(new org.jfree.data.time.Day(lastDate));
            }
        }
    }
    periodaxis.setTickMarkOutsideLength(0.0F);
    plot.setDomainAxis(periodaxis);

    // set outline
    AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) plot.getRenderer();
    if (renderer instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) renderer;
        r.setDrawSeriesLineAsPath(true);
        r.setShapesVisible(true);
        r.setShapesFilled(true);
    } else if (renderer instanceof XYBarRenderer) {
        //XYBarRenderer r = (XYBarRenderer) renderer;
        ClusteredXYBarRenderer r = new ClusteredXYBarRenderer();
        r.setDrawBarOutline(true);
        if (smallFontInDomainAxis && !canUseNormalFontSize(width))
            r.setMargin(0.05);
        else
            r.setMargin(0.10);
        plot.setRenderer(r);
        renderer = r;
    }

    // item labels
    if (itemLabelsVisible) {
        plot.getRangeAxis().setUpperMargin(0.2);
        renderer.setItemLabelGenerator(new XYItemLabelGenerator() {
            private static final long serialVersionUID = 1L;

            public String generateLabel(XYDataset dataset, int series, int item) {
                Number n = dataset.getY(series, item);
                if (n.doubleValue() != 0)
                    return n.toString();
                return "";
            }

        });
        renderer.setItemLabelFont(new Font("SansSerif", Font.PLAIN, 8));
        renderer.setItemLabelsVisible(true);
    }

    BufferedImage img = chart.createBufferedImage(width, height);
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ImageIO.write(img, "png", out);
    } catch (IOException e) {
        LOG.warn("Error occurred while generating SiteStats chart image data", e);
    }
    return out.toByteArray();
}

From source file:com.comcast.cmb.common.controller.EndpointServlet.java

private byte[] generateChart(EndpointMetrics metric, String id) throws IOException {

    XYSeries series = new XYSeries("Test Run");

    for (int i = 0; i < metric.timeSeries.size(); i++) {
        series.add(i, metric.timeSeries.get(i));
    }//from   w  ww  .  j  a  va 2  s.c  o m

    XYSeriesCollection dataset = new XYSeriesCollection(series);

    JFreeChart chart = ChartFactory.createXYBarChart(
            "Start: " + metric.startTime + " End: " + metric.endTime + " Message Count: " + metric.messageCount,
            "Test Second", false, "Number of Messages", dataset, PlotOrientation.VERTICAL, true, true, false);

    //File file = new File(getServletContext().getRealPath("WEB-INF" + "/" + id + ".jpeg"));
    //ChartUtilities.saveChartAsJPEG(file, chart, 1600, 400);
    //byte b[] = Files.toByteArray(file);
    //return b;

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ChartUtilities.writeChartAsJPEG(bos, chart, 2400, 400);
    return bos.toByteArray();
}