Example usage for org.jfree.chart ChartFactory createHistogram

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

Introduction

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

Prototype

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

Source Link

Document

Creates a histogram chart.

Usage

From source file:com.compomics.cell_coord.gui.controller.computation.ComputationDataController.java

/**
 *
 * @param track/*from   w ww.j a v a  2 s. com*/
 */
private void plotDisplacements(Track track) {
    double[] values = ArrayUtils.toPrimitive(ComputationUtils.excludeNullValues(track.getStepDisplacements()));
    HistogramDataset histogramDataset = new HistogramDataset();
    histogramDataset.addSeries("", values, 5);
    String title = "displacements for track: " + track.getTrackid();
    JFreeChart jFreeChart = ChartFactory.createHistogram(title, "displ", "count", histogramDataset,
            PlotOrientation.VERTICAL, true, true, true);
    ChartPanel chartPanel = new ChartPanel(jFreeChart);
    computationDataPanel.getDisplPlotPanel().removeAll();
    computationDataPanel.getDisplPlotPanel().add(chartPanel, gridBagConstraints);
    computationDataPanel.getDisplPlotPanel().revalidate();
    computationDataPanel.getDisplPlotPanel().repaint();
}

From source file:org.deegree.test.gui.StressTestController.java

private void drawDiagram(HttpServletResponse response, int width, int height) throws IOException {

    int n = resultData.size();
    double[] values = new double[n];
    for (int i = 0; i < n; i++)
        values[i] = resultData.get(i).getTimeElapsed() / 1000.0;

    HistogramDataset dataset = new HistogramDataset();
    dataset.addSeries(new Double(1.0), values, n);

    JFreeChart chart = ChartFactory.createHistogram("timeVSfreq", "time", "frequency", dataset,
            PlotOrientation.VERTICAL, true, true, true);

    ChartRenderingInfo info = new ChartRenderingInfo();
    BufferedImage buf = chart.createBufferedImage(width, height, 1, info);

    response.setContentType("image/jpeg");
    OutputStream out = response.getOutputStream();
    ImageIO.write(buf, "jpg", out);
    out.close();/*from w w  w .  j av a 2s.com*/

}

From source file:org.locationtech.udig.processingtoolbox.tools.HistogramDialog.java

private void updateChart(SimpleFeatureCollection features, String field) {
    int bin = spinner.getSelection();

    double[] values = getValues(features, field);
    HistogramDataset dataset = new HistogramDataset();
    dataset.addSeries(field, values, bin, minMaxVisitor.getMinX(), minMaxVisitor.getMaxX());
    dataset.setType(histogramType);/*from   w w  w  .j a  v a 2  s . co m*/

    JFreeChart chart = ChartFactory.createHistogram(EMPTY, null, null, dataset, PlotOrientation.VERTICAL, false,
            false, false);

    // 1. Create a single plot containing both the scatter and line
    chart.setBackgroundPaint(java.awt.Color.WHITE);
    chart.setBorderVisible(false);

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setForegroundAlpha(0.85F);
    plot.setBackgroundPaint(java.awt.Color.WHITE);
    plot.setOrientation(PlotOrientation.VERTICAL);

    plot.setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
    plot.setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);

    int fontStyle = java.awt.Font.BOLD;
    FontData fontData = getShell().getDisplay().getSystemFont().getFontData()[0];

    NumberAxis valueAxis = new NumberAxis(cboField.getText());
    valueAxis.setLabelFont(new Font(fontData.getName(), fontStyle, 12));
    valueAxis.setTickLabelFont(new Font(fontData.getName(), fontStyle, 10));

    valueAxis.setAutoRange(false);
    valueAxis.setRange(minMaxVisitor.getMinX(), minMaxVisitor.getMaxX());

    String rangeAxisLabel = histogramType == HistogramType.FREQUENCY ? "Frequency" : "Ratio"; //$NON-NLS-1$ //$NON-NLS-2$
    NumberAxis rangeAxis = new NumberAxis(rangeAxisLabel);
    rangeAxis.setLabelFont(new Font(fontData.getName(), fontStyle, 12));
    rangeAxis.setTickLabelFont(new Font(fontData.getName(), fontStyle, 10));
    if (histogramType == HistogramType.FREQUENCY) {
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }

    XYBarRenderer renderer = (XYBarRenderer) plot.getRenderer();
    renderer.setShadowVisible(false);
    CustomXYBarPainter.selectedColumn = -1; // init
    renderer.setBarPainter(new CustomXYBarPainter());
    renderer.setAutoPopulateSeriesFillPaint(true);
    renderer.setAutoPopulateSeriesPaint(true);
    renderer.setShadowXOffset(3);
    renderer.setMargin(0.01);
    renderer.setBaseItemLabelsVisible(true);

    ItemLabelPosition pos = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.TOP_CENTER);
    renderer.setBasePositiveItemLabelPosition(pos);

    XYToolTipGenerator plotToolTip = new StandardXYToolTipGenerator();
    renderer.setBaseToolTipGenerator(plotToolTip);

    // color
    GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, java.awt.Color.GRAY, 0.0f, 0.0f,
            java.awt.Color.LIGHT_GRAY);
    renderer.setSeriesPaint(0, gp0);

    plot.setDomainAxis(0, valueAxis);
    plot.setRangeAxis(0, rangeAxis);

    // 3. Setup line
    // Create the line data, renderer, and axis
    XYItemRenderer lineRenderer = new XYLineAndShapeRenderer(true, false); // Lines only
    lineRenderer.setSeriesPaint(0, java.awt.Color.RED);
    lineRenderer.setSeriesStroke(0, new BasicStroke(2f));

    // Set the line data, renderer, and axis into plot
    NumberAxis xLineAxis = new NumberAxis(EMPTY);
    xLineAxis.setTickMarksVisible(false);
    xLineAxis.setTickLabelsVisible(false);
    xLineAxis.setAutoRange(false);

    NumberAxis yLineAxis = new NumberAxis(EMPTY);
    yLineAxis.setTickMarksVisible(false);
    yLineAxis.setTickLabelsVisible(false);
    yLineAxis.setAutoRange(false);

    double maxYValue = Double.MIN_VALUE;
    for (int i = 0; i < dataset.getItemCount(0); i++) {
        maxYValue = Math.max(maxYValue, dataset.getYValue(0, i));
    }

    XYSeriesCollection lineDatset = new XYSeriesCollection();

    // Vertical Average
    XYSeries vertical = new XYSeries("Average"); //$NON-NLS-1$
    vertical.add(minMaxVisitor.getAverageX(), 0);
    vertical.add(minMaxVisitor.getAverageX(), maxYValue);
    lineDatset.addSeries(vertical);

    plot.setDataset(1, lineDatset);
    plot.setRenderer(1, lineRenderer);
    plot.setDomainAxis(1, xLineAxis);
    plot.setRangeAxis(1, yLineAxis);

    // Map the line to the second Domain and second Range
    plot.mapDatasetToDomainAxis(1, 0);
    plot.mapDatasetToRangeAxis(1, 0);

    chartComposite.setChart(chart);
    chartComposite.forceRedraw();
}

From source file:net.sf.jsfcomp.chartcreator.utils.ChartUtils.java

public static JFreeChart createChartWithXYDataSet(ChartData chartData) {
    XYDataset dataset = (XYDataset) chartData.getDatasource();
    String type = chartData.getType();
    String xAxis = chartData.getXlabel();
    String yAxis = chartData.getYlabel();
    boolean legend = chartData.isLegend();

    JFreeChart chart = null;/*  ww  w.j  av  a2  s. c  o  m*/
    PlotOrientation plotOrientation = ChartUtils.getPlotOrientation(chartData.getOrientation());

    if (type.equalsIgnoreCase("timeseries")) {
        chart = ChartFactory.createTimeSeriesChart("", xAxis, yAxis, dataset, legend, true, false);
    } else if (type.equalsIgnoreCase("xyline")) {
        chart = ChartFactory.createXYLineChart("", xAxis, yAxis, dataset, plotOrientation, legend, true, false);
    } else if (type.equalsIgnoreCase("polar")) {
        chart = ChartFactory.createPolarChart("", dataset, legend, true, false);
    } else if (type.equalsIgnoreCase("scatter")) {
        chart = ChartFactory.createScatterPlot("", xAxis, yAxis, dataset, plotOrientation, legend, true, false);
    } else if (type.equalsIgnoreCase("xyarea")) {
        chart = ChartFactory.createXYAreaChart("", xAxis, yAxis, dataset, plotOrientation, legend, true, false);
    } else if (type.equalsIgnoreCase("xysteparea")) {
        chart = ChartFactory.createXYStepAreaChart("", xAxis, yAxis, dataset, plotOrientation, legend, true,
                false);
    } else if (type.equalsIgnoreCase("xystep")) {
        chart = ChartFactory.createXYStepChart("", xAxis, yAxis, dataset, plotOrientation, legend, true, false);
    } else if (type.equalsIgnoreCase("bubble")) {
        chart = ChartFactory.createBubbleChart("", xAxis, yAxis, (XYZDataset) dataset, plotOrientation, legend,
                true, false);
    } else if (type.equalsIgnoreCase("candlestick")) {
        chart = ChartFactory.createCandlestickChart("", xAxis, yAxis, (OHLCDataset) dataset, legend);
    } else if (type.equalsIgnoreCase("boxandwhisker")) {
        chart = ChartFactory.createBoxAndWhiskerChart("", xAxis, yAxis, (BoxAndWhiskerXYDataset) dataset,
                legend);
    } else if (type.equalsIgnoreCase("highlow")) {
        chart = ChartFactory.createHighLowChart("", xAxis, yAxis, (OHLCDataset) dataset, legend);
    } else if (type.equalsIgnoreCase("histogram")) {
        chart = ChartFactory.createHistogram("", xAxis, yAxis, (IntervalXYDataset) dataset, plotOrientation,
                legend, true, false);
    } else if (type.equalsIgnoreCase("wind")) {
        chart = ChartFactory.createWindPlot("", xAxis, yAxis, (WindDataset) dataset, legend, true, false);
    }

    if (chart.getPlot() instanceof XYPlot) {
        chart.getXYPlot().setDomainGridlinesVisible(chartData.isDomainGridLines());
        chart.getXYPlot().setRangeGridlinesVisible(chartData.isRangeGridLines());

        if (chartData.getGenerateMap() != null)
            chart.getXYPlot().getRenderer().setURLGenerator(new StandardXYURLGenerator(""));
    }

    setXYSeriesColors(chart, chartData);

    setXYExtensions(chart, chartData);

    return chart;
}

From source file:com.compomics.cell_coord.gui.controller.computation.ComputationDataController.java

/**
 *
 * @param track/* www.j  a v  a2 s  .c om*/
 */
private void plotAngles(Track track) {
    double[] values = ArrayUtils.toPrimitive(ComputationUtils.excludeNullValues(track.getAngles()));
    HistogramDataset histogramDataset = new HistogramDataset();
    histogramDataset.addSeries("", values, 5);
    String title = "angles for track: " + track.getTrackid();
    JFreeChart jFreeChart = ChartFactory.createHistogram(title, "angle", "count", histogramDataset,
            PlotOrientation.VERTICAL, true, true, true);
    ChartPanel chartPanel = new ChartPanel(jFreeChart);
    computationDataPanel.getAnglePlotPanel().removeAll();
    computationDataPanel.getAnglePlotPanel().add(chartPanel, gridBagConstraints);
    computationDataPanel.getAnglePlotPanel().revalidate();
    computationDataPanel.getAnglePlotPanel().repaint();
}

From source file:org.jfree.chart.demo.ThumbnailDemo1.java

private static JFreeChart createChart5(IntervalXYDataset intervalxydataset) {
    JFreeChart jfreechart = ChartFactory.createHistogram("Histogram Demo 1", null, null, intervalxydataset,
            PlotOrientation.VERTICAL, true, true, false);
    jfreechart.setBackgroundPaint(Color.white);
    XYPlot xyplot = (XYPlot) jfreechart.getPlot();
    xyplot.setBackgroundPaint(Color.lightGray);
    xyplot.setDomainGridlinePaint(Color.white);
    xyplot.setRangeGridlinePaint(Color.white);
    xyplot.setForegroundAlpha(0.85F);//from www  .j  a  va  2  s. co  m
    XYBarRenderer xybarrenderer = (XYBarRenderer) xyplot.getRenderer();
    xybarrenderer.setDrawBarOutline(false);
    return jfreechart;
}

From source file:v800_trainer.JHistogram.java

public JPanel StartHistoHm(JCicloTronic JTronicHandle) {

    boolean Summenhisto;
    int von = 0;//  ww w.j a v  a2 s . c o m
    int bis = 0;
    int num = 0;
    int selected;
    int single;
    int Gruppen = 0;
    int i = 100;
    int j = 10;
    int m = 0;
    int n = 0;
    int Linecount = 0;
    int Anzahl = 1;

    JFreeChart chart;

    double DummyData[] = new double[1];

    selected = JTronicHandle.Auswahl_Histogramm.getSelectedIndex();
    Summenhisto = JTronicHandle.Summenhistogramm_Check.isSelected();

    chart = ChartFactory.createHistogram("", "Steigung [m/min]", "Hufigkeit", new HistogramDataset(),
            PlotOrientation.HORIZONTAL, true, true, true);

    chart.setBackgroundPaint(Color.white);

    JTronicHandle.applyChartTheme(chart);

    XYPlot plot = chart.getXYPlot();
    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);

    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.getRangeAxis().setFixedDimension(15.0);

    ArrayList Bufferarray = new ArrayList();
    double Buffer;

    if (selected == 0) {
        single = 1;
    } else {
        single = 0;
        Summenhisto = false;
    }
    ;

    try {
        von = Integer.parseInt(JTronicHandle.Properties.getProperty("HistovonHm", "100"));
        bis = Integer.parseInt(JTronicHandle.Properties.getProperty("HistobisHm", "200"));
        Gruppen = Integer.parseInt(JTronicHandle.Properties.getProperty("HistostepHm", "10"));
        Anzahl = (JTronicHandle.Auswahl_Histogramm.getItemCount() - 2) * single + 1;
        for (j = 0; j < Anzahl; j++) {
            if (single == 1) {
                selected = j + 1;
            }
            if (!Summenhisto) {
                num = JTronicHandle.Statistikhandle.TourData[selected].Datenpunkte;
            } else {
                num += JTronicHandle.Statistikhandle.TourData[selected].Datenpunkte;
            }

            n = 0;
            if (!Summenhisto) {
                create_Start_Stop(JTronicHandle, selected); //die limits einer gezoomten Graphik ermitteln

                for (i = start; i < stop; i++) {
                    Buffer = (double) JTronicHandle.Statistikhandle.TourData[selected].Steigm_gesZeit[i];
                    if (Buffer >= von && Buffer <= bis) {
                        Bufferarray.add(Buffer);
                    }
                }
            } else {
                for (i = 0; i < j + 1; i++) {
                    create_Start_Stop(JTronicHandle, i + 1);
                    for (m = start; m < stop; m++) {
                        Buffer = (double) JTronicHandle.Statistikhandle.TourData[i + 1].Steigm_gesZeit[m];
                        if (Buffer >= von && Buffer <= bis) {
                            Bufferarray.add(Buffer);
                        }

                    }

                }
            }

            DummyData = new double[Bufferarray.size()];

            for (i = 0; i < Bufferarray.size(); i++) {
                DummyData[i] = new Double(Bufferarray.get(i).toString());
            }

            if (!Summenhisto) {
                HistogramDataset histoHM = new HistogramDataset();
                histoHM.addSeries(
                        "" + JTronicHandle.Statistikhandle.TourData[selected].Tag + "."
                                + JTronicHandle.Statistikhandle.TourData[selected].Monat + "."
                                + JTronicHandle.Statistikhandle.TourData[selected].Jahr,
                        DummyData, Gruppen, (double) von, (double) bis);
                histoHM.setType(HistogramType.RELATIVE_FREQUENCY);
                plot.setDataset(Linecount, histoHM);
                plot.mapDatasetToRangeAxis(Linecount, 0);
                XYBarRenderer renderer = new XYBarRenderer();
                renderer.setDrawBarOutline(true);

                renderer.setSeriesPaint(0, getColour(Linecount, (int) 255 / Anzahl));

                renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
                plot.setRenderer(Linecount, renderer);

            }
            Linecount++;
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "StartHistoSp\nFehler: Hm " + e + " " + i + " " + j, "Achtung!",
                JOptionPane.ERROR_MESSAGE);
    }

    if (Summenhisto) {
        HistogramDataset histoHM = new HistogramDataset();
        histoHM.addSeries("Summenhistogram", DummyData, Gruppen, (double) von, (double) bis);
        histoHM.setType(HistogramType.RELATIVE_FREQUENCY);

        plot.setDataset(0, histoHM);
        plot.mapDatasetToRangeAxis(0, 0);
        XYItemRenderer renderer = new XYBarRenderer();
        renderer.setSeriesPaint(0, Color.blue);
        renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());

        plot.setRenderer(0, renderer);
    }
    chart.setPadding(padding);
    ChartPanel Panel = new ChartPanel(chart);

    return Panel;
}

From source file:compecon.dashboard.panel.HouseholdsPanel.java

protected JFreeChart createIncomeDistributionPanel(Currency currency) {
    IntervalXYDataset dataset = ApplicationContext.getInstance().getModelRegistry()
            .getNationalEconomyModel(currency).householdsModel.incomeDistributionModel.getHistogramDataset();
    JFreeChart incomeDistributionChart = ChartFactory.createHistogram("Income Distribution", "Income",
            "% Households at Income", dataset, PlotOrientation.VERTICAL, true, false, false);
    return incomeDistributionChart;
}

From source file:weka.gui.beans.JFreeChartOffscreenChartRenderer.java

/**
 * Render histogram(s) (numeric attribute) or bar chart (nominal attribute).
 * Some implementations may not be able to render more than one histogram/bar
 * on the same chart - the implementation can either throw an exception or
 * just process the first series in this case.
 * //from   w w  w. j  a v a2 s  .  c  o m
 * @param width the width of the resulting chart in pixels
 * @param height the height of the resulting chart in pixels
 * @param series a list of Instances - one for each series to be plotted
 * @param attsToPlot the attribute to plot corresponding to the Instances in
 *          the series list
 * @param optionalArgs optional arguments to the renderer (may be null)
 * 
 * @return a BufferedImage containing the chart
 * @throws Exception if there is a problem rendering the chart
 */
public BufferedImage renderHistogram(int width, int height, List<Instances> series, String attToPlot,
        List<String> additionalArgs) throws Exception {

    String plotTitle = "Bar Chart";
    String userTitle = getOption(additionalArgs, "-title");
    plotTitle = (userTitle != null) ? userTitle : plotTitle;
    String colorAtt = getOption(additionalArgs, "-color");
    String pareto = getOption(additionalArgs, "-pareto");

    boolean doPareto = false;
    if (pareto != null && pareto.length() == 0 && series.size() == 1) {
        doPareto = true;
    }

    if (series.size() == 1 && colorAtt != null && colorAtt.length() > 0) {
        int colIndex = getIndexOfAttribute(series.get(0), colorAtt);

        if (colIndex >= 0 && series.get(0).attribute(colIndex).isNominal() && !doPareto) {
            // split single series out into multiple instances objects - one
            // per class
            series = splitToClasses(series.get(0), colIndex);
            for (Instances insts : series) {
                insts.setClassIndex(colIndex);
            }
        }
    }

    Instances masterInstances = series.get(0);
    int attIndex = getIndexOfAttribute(masterInstances, attToPlot);
    if (attIndex < 0) {
        attIndex = 0;
    }

    if (!(series.get(0).attribute(attIndex).isNominal()
            || series.get(0).attribute(attIndex).isRelationValued())) {
        doPareto = false;
    }

    // Do a pareto chart
    if (doPareto) {
        final DefaultKeyedValues data = new DefaultKeyedValues();
        AttributeStats attStats = masterInstances.attributeStats(attIndex);
        double[] attValFreqs = attStats.nominalWeights;
        for (int i = 0; i < attValFreqs.length; i++) {
            Number freq = new Double(attValFreqs[i]);
            data.addValue(masterInstances.attribute(attIndex).value(i), freq);
        }

        data.sortByValues(SortOrder.DESCENDING);
        final KeyedValues cumulative = DataUtilities.getCumulativePercentages(data);
        final CategoryDataset dataset = DatasetUtilities
                .createCategoryDataset(masterInstances.attribute(attIndex).name(), data);

        final JFreeChart chart = ChartFactory.createBarChart(plotTitle,
                masterInstances.attribute(attIndex).name(), "Fequency/weight mass", dataset,
                PlotOrientation.VERTICAL, true, false, false);

        final CategoryPlot plot = chart.getCategoryPlot();

        final CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setLowerMargin(0.02);
        domainAxis.setUpperMargin(0.02);

        LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();
        CategoryDataset dataset2 = DatasetUtilities.createCategoryDataset("Cumulative", cumulative);
        final NumberAxis axis2 = new NumberAxis("Percent");
        axis2.setNumberFormatOverride(NumberFormat.getPercentInstance());
        // plot.
        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, dataset2);
        plot.setRenderer(1, renderer2);
        plot.mapDatasetToRangeAxis(1, 1);
        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

        chart.setBackgroundPaint(java.awt.Color.white);
        BufferedImage image = chart.createBufferedImage(width, height);
        return image;
    }

    boolean seriesAreClasses = false;
    int classIndex = masterInstances.classIndex();

    if (classIndex >= 0 && !masterInstances.attribute(classIndex).isNumeric()
            && !masterInstances.attribute(classIndex).isRelationValued()
            && masterInstances.attributeStats(classIndex).distinctCount == 1) {
        // series correspond to class labels (assume that subsequent series only
        // contain instances of one class)...
        seriesAreClasses = true;
    }

    // bar chart for a nominal attribute
    if (masterInstances.attribute(attIndex).isNominal() || masterInstances.attribute(attIndex).isString()) {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        // do the master series
        String masterSeriesTitle = masterInstances.relationName();
        if (seriesAreClasses) {
            for (int i = 0; i < masterInstances.numInstances(); i++) {
                Instance current = masterInstances.instance(i);
                if (!current.isMissing(classIndex)) {
                    masterSeriesTitle = current.stringValue(classIndex);
                    break;
                }
            }
        }

        AttributeStats attStats = masterInstances.attributeStats(attIndex);
        double[] attValFreqs = attStats.nominalWeights;
        for (int i = 0; i < attValFreqs.length; i++) {
            Number freq = new Double(attValFreqs[i]);
            dataset.addValue(freq, masterSeriesTitle, masterInstances.attribute(attIndex).value(i));
        }

        // any subsequent series
        for (int i = 1; i < series.size(); i++) {
            Instances nextSeries = series.get(i);

            String seriesTitle = nextSeries.relationName();

            if (seriesAreClasses) {
                for (int j = 0; j < nextSeries.numInstances(); j++) {
                    Instance current = nextSeries.instance(j);
                    if (!current.isMissing(classIndex)) {
                        seriesTitle = current.stringValue(classIndex);
                        break;
                    }
                }

                attStats = nextSeries.attributeStats(attIndex);
                attValFreqs = attStats.nominalWeights;
                for (int j = 0; j < attValFreqs.length; j++) {
                    Number freq = new Double(attValFreqs[j]);
                    dataset.addValue(freq, seriesTitle, nextSeries.attribute(attIndex).value(j));
                }
            }
        }

        JFreeChart chart = null;

        if (series.size() == 1) {
            chart = ChartFactory.createBarChart(plotTitle, masterInstances.attribute(attIndex).name(),
                    "Fequency/weight mass", dataset, PlotOrientation.VERTICAL, true, false, false);
        } else {
            chart = ChartFactory.createStackedBarChart(plotTitle, masterInstances.attribute(attIndex).name(),
                    "Fequency/weight mass", dataset, PlotOrientation.VERTICAL, true, false, false);
        }

        chart.setBackgroundPaint(java.awt.Color.white);
        BufferedImage image = chart.createBufferedImage(width, height);
        return image;

    } else {
        // histogram for numeric attributes
        HistogramDataset dataset = new HistogramDataset();

        // combine all series in order to get overall std dev, and range
        Instances temp = new Instances(masterInstances);
        for (int i = 1; i < series.size(); i++) {
            Instances additional = series.get(i);
            for (Instance tempI : additional) {
                temp.add(tempI);
            }
        }

        AttributeStats stats = temp.attributeStats(attIndex);
        Stats numericStats = stats.numericStats;
        double intervalWidth = 3.49 * numericStats.stdDev * StrictMath.pow(temp.numInstances(), (-1.0 / 3.0));
        double range = numericStats.max - numericStats.min;
        int numBins = StrictMath.max(1, (int) StrictMath.round(range / intervalWidth));

        // do the master series
        String masterSeriesTitle = masterInstances.relationName();
        if (seriesAreClasses) {
            for (int i = 0; i < masterInstances.numInstances(); i++) {
                Instance current = masterInstances.instance(i);
                if (!current.isMissing(current.classAttribute())) {
                    masterSeriesTitle = current.stringValue(current.classAttribute());
                    break;
                }
            }
        }

        // have to set min, max and num bins (using heuristic from AttSummPanel).
        // Make sure
        // to set series length to num instances - num missing values for att
        stats = masterInstances.attributeStats(attIndex);
        /*
         * numericStats = stats.numericStats; //numericStats.calculateDerived();
         * intervalWidth = StrictMath.max(1, 3.49 * numericStats.stdDev *
         * StrictMath.pow(masterInstances.numInstances(), (-1.0/3.0)));
         */

        double[] seriesVals = new double[masterInstances.numInstances() - stats.missingCount];
        int count = 0;
        for (int i = 0; i < masterInstances.numInstances(); i++) {
            Instance current = masterInstances.instance(i);
            if (!current.isMissing(attIndex)) {
                seriesVals[count++] = current.value(attIndex);
            }
        }

        dataset.addSeries(masterSeriesTitle, seriesVals, numBins, numericStats.min, numericStats.max);

        // any subsequent series
        for (int i = 1; i < series.size(); i++) {
            Instances nextSeries = series.get(i);

            String seriesTitle = nextSeries.relationName();

            if (seriesAreClasses) {
                for (int j = 0; j < nextSeries.numInstances(); j++) {
                    Instance current = nextSeries.instance(j);
                    if (!current.isMissing(nextSeries.classAttribute())) {
                        seriesTitle = current.stringValue(nextSeries.classAttribute());
                        break;
                    }
                }
            }

            stats = nextSeries.attributeStats(attIndex);
            /*
             * numericStats = stats.numericStats; //
             * numericStats.calculateDerived(); intervalWidth = StrictMath.max(1,
             * 3.49 * numericStats.stdDev *
             * StrictMath.pow(masterInstances.numInstances(), (-1.0/3.0))); range =
             * numericStats.max - numericStats.min; numBins = StrictMath.max(1,
             * (int) StrictMath.round(range / intervalWidth));
             */
            seriesVals = new double[nextSeries.numInstances() - stats.missingCount];
            count = 0;
            for (int j = 0; j < nextSeries.numInstances(); j++) {
                Instance current = nextSeries.instance(j);
                if (!current.isMissing(attIndex)) {
                    seriesVals[count++] = current.value(attIndex);
                }
            }

            dataset.addSeries(seriesTitle, seriesVals, numBins, numericStats.min, numericStats.max);
        }

        JFreeChart chart = ChartFactory.createHistogram(plotTitle, masterInstances.attribute(attIndex).name(),
                null, dataset, PlotOrientation.VERTICAL, true, false, false);

        // chart.setBackgroundPaint(java.awt.Color.white);
        XYPlot xyplot = (XYPlot) chart.getPlot();
        xyplot.setForegroundAlpha(0.50F);
        XYBarRenderer xybarrenderer = (XYBarRenderer) xyplot.getRenderer();
        xybarrenderer.setDrawBarOutline(false);
        xybarrenderer.setShadowVisible(false);

        BufferedImage image = chart.createBufferedImage(width, height);
        return image;
    }
}

From source file:org.matsim.contrib.parking.parkingchoice.lib.GeneralLib.java

public static void generateHistogram(String fileName, double[] value, int numberOfBins, String title,
        String xLabel, String yLabel) {
    HistogramDataset dataset = new HistogramDataset();
    dataset.setType(HistogramType.FREQUENCY);
    dataset.addSeries(title, value, numberOfBins);
    String plotTitle = title;/*from   w  w  w  .java 2s  .c om*/
    String xaxis = xLabel;
    String yaxis = yLabel;
    PlotOrientation orientation = PlotOrientation.VERTICAL;
    boolean show = false;
    boolean toolTips = false;
    boolean urls = false;
    JFreeChart chart = ChartFactory.createHistogram(plotTitle, xaxis, yaxis, dataset, orientation, show,
            toolTips, urls);
    int width = 500;
    int height = 300;
    try {
        ChartUtilities.saveChartAsPNG(new File(fileName), chart, width, height);
    } catch (IOException e) {

    }
}