Example usage for org.jfree.data.statistics HistogramDataset addSeries

List of usage examples for org.jfree.data.statistics HistogramDataset addSeries

Introduction

In this page you can find the example usage for org.jfree.data.statistics HistogramDataset addSeries.

Prototype

public void addSeries(Comparable key, double[] values, int bins) 

Source Link

Document

Adds a series to the dataset, using the specified number of bins, and sends a DatasetChangeEvent to all registered listeners.

Usage

From source file:MSUmpire.DIA.MixtureModelKDESemiParametric.java

public void GeneratePlot(String pngfile) throws IOException {
    String modelfile = FilenameUtils.getFullPath(pngfile) + "/" + FilenameUtils.getBaseName(pngfile)
            + "_ModelPoints.txt";
    FileWriter writer = new FileWriter(modelfile);

    double[] IDObs = new double[IDEmpiricalDist.getN()];
    double[] DecoyObs = new double[DecoyEmpiricalDist.getN()];

    for (int i = 0; i < IDEmpiricalDist.getN(); i++) {
        IDObs[i] = IDEmpiricalDist.getObs(i);
    }//from  w  w  w .  j  av a  2 s .c  o  m
    for (int i = 0; i < DecoyEmpiricalDist.getN(); i++) {
        DecoyObs[i] = DecoyEmpiricalDist.getObs(i);
    }

    XYSeries model1 = new XYSeries("Incorrect matches");
    XYSeries model2 = new XYSeries("Correct matches");
    XYSeries model3 = new XYSeries("All target hits");

    writer.write("UScore\tModel\tCorrect\tDecoy\n");
    for (int i = 0; i < NoBinPoints; i++) {
        model1.add(model_kde_x[i], decoy_kde_y[i]);
        model2.add(model_kde_x[i], correct_kde_y[i]);
        model3.add(model_kde_x[i], model_kde_y[i]);
        writer.write(model_kde_x[i] + "\t" + model_kde_y[i] + "\t" + correct_kde_y[i] + "\t" + decoy_kde_y[i]
                + "\n");
    }
    writer.close();

    MixtureModelProb = new float[NoBinPoints + 1][3];
    float positiveaccu = 0f;
    float negativeaccu = 0f;

    MixtureModelProb[0][0] = (float) model2.getMaxX() + Float.MIN_VALUE;
    MixtureModelProb[0][1] = 1f;
    MixtureModelProb[0][2] = 1f;

    for (int i = 1; i < NoBinPoints + 1; i++) {
        double positiveNumber = correct_kde_y[NoBinPoints - i];
        double negativeNumber = decoy_kde_y[NoBinPoints - i];
        MixtureModelProb[i][0] = (float) model_kde_x[NoBinPoints - i];
        positiveaccu += positiveNumber;
        negativeaccu += negativeNumber;
        MixtureModelProb[i][2] = 0.999999f * (float) (positiveNumber / (negativeNumber + positiveNumber));
        MixtureModelProb[i][1] = 0.999999f * (float) (positiveaccu / (negativeaccu + positiveaccu));
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(model1);
    dataset.addSeries(model2);
    dataset.addSeries(model3);

    HistogramDataset histogramDataset = new HistogramDataset();
    histogramDataset.setType(HistogramType.SCALE_AREA_TO_1);
    histogramDataset.addSeries("ID hits", IDObs, 100);
    histogramDataset.addSeries("Decoy hits", DecoyObs, 100);
    //histogramDataset.addSeries("Model hits", ModelObs, 100);

    JFreeChart chart = ChartFactory.createHistogram(FilenameUtils.getBaseName(pngfile), "Score", "Hits",
            histogramDataset, PlotOrientation.VERTICAL, true, false, false);
    XYPlot plot = chart.getXYPlot();

    NumberAxis domain = (NumberAxis) plot.getDomainAxis();
    domain.setRange(min, max);
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setForegroundAlpha(0.8f);
    chart.setBackgroundPaint(Color.white);

    XYLineAndShapeRenderer render = new XYLineAndShapeRenderer();

    plot.setDataset(1, dataset);
    plot.setRenderer(1, render);
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    try {
        ChartUtilities.saveChartAsPNG(new File(pngfile), chart, 1000, 600);
    } catch (IOException e) {
    }
}

From source file:org.openmrs.web.controller.ConceptStatsFormController.java

/**
 * Called prior to form display. Allows for data to be put in the request to be used in the view
 *
 * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
 *//*ww w.j  a  va2  s.c o  m*/
protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception {

    Map<String, Object> map = new HashMap<String, Object>();
    if (!Context.hasPrivilege("View Observations")) {
        return map;
    }

    MessageSourceAccessor msa = getMessageSourceAccessor();
    Locale locale = Context.getLocale();
    ConceptService cs = Context.getConceptService();
    String conceptId = request.getParameter("conceptId");
    //List<Obs> obs = new Vector<Obs>();
    //List<Obs> obsAnswered = new Vector<Obs>();

    if (conceptId != null) {
        Concept concept = cs.getConcept(Integer.valueOf(conceptId));
        ObsService obsService = Context.getObsService();

        if (concept != null) {

            // previous/next ids for links
            map.put("previousConcept", cs.getPrevConcept(concept));
            map.put("nextConcept", cs.getNextConcept(concept));

            //obs = obsService.getObservations(concept, "valueNumeric, obsId");
            //obsAnswered = obsService.getObservationsAnsweredByConcept(concept);

            if (ConceptDatatype.NUMERIC.equals(concept.getDatatype().getHl7Abbreviation())) {
                map.put("displayType", "numeric");

                List<Obs> numericAnswers = obsService.getObservations(null, null,
                        Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null,
                        Collections.singletonList("valueNumeric"), null, null, null, null, false);

                if (numericAnswers.size() > 0) {
                    Double min = numericAnswers.get(0).getValueNumeric();
                    Double max = (Double) numericAnswers.get(numericAnswers.size() - 1).getValueNumeric();
                    Double median = (Double) numericAnswers.get(numericAnswers.size() / 2).getValueNumeric();

                    Map<Double, Integer> counts = new HashMap<Double, Integer>(); // counts for the histogram
                    Double total = 0.0; // sum of values. used for mean

                    // dataset setup for lineChart
                    TimeSeries timeSeries = new TimeSeries(concept.getName().getName(), Day.class);
                    TimeSeriesCollection timeDataset = new TimeSeriesCollection();
                    Calendar calendar = Calendar.getInstance();

                    // array for histogram
                    double[] obsNumerics = new double[(numericAnswers.size())];

                    Integer i = 0;
                    for (Obs obs : numericAnswers) {
                        Date date = (Date) obs.getObsDatetime();
                        Double value = (Double) obs.getValueNumeric();

                        // for mean calculation
                        total += value;

                        // for histogram
                        obsNumerics[i++] = value;
                        Integer count = counts.get(value);
                        counts.put(value, count == null ? 1 : count + 1);

                        // for line chart
                        calendar.setTime(date);
                        Day day = new Day(calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.MONTH) + 1, // January = 0 
                                calendar.get(Calendar.YEAR) < 1900 ? 1900 : calendar.get(Calendar.YEAR) // jfree chart doesn't like the 19th century
                        );
                        timeSeries.addOrUpdate(day, value);
                    }

                    Double size = new Double(numericAnswers.size());
                    Double mean = total / size;

                    map.put("size", numericAnswers.size());
                    map.put("min", min);
                    map.put("max", max);
                    map.put("mean", mean);
                    map.put("median", median);

                    // create histogram chart
                    HistogramDataset histDataset = new HistogramDataset(); // dataset for histogram
                    histDataset.addSeries(concept.getName().getName(), obsNumerics, counts.size());

                    JFreeChart histogram = ChartFactory.createHistogram(concept.getName().getName(),
                            msa.getMessage("Concept.stats.histogramDomainAxisTitle"),
                            msa.getMessage("Concept.stats.histogramRangeAxisTitle"), histDataset,
                            PlotOrientation.VERTICAL, false, true, false);
                    map.put("histogram", histogram);

                    if (size > 25) {
                        // calculate 98th percentile of the data:
                        Double x = 0.98;
                        Integer xpercentile = (int) (x * size);
                        Double upperQuartile = numericAnswers.get(xpercentile).getValueNumeric();
                        Double lowerQuartile = numericAnswers.get((int) (size - xpercentile)).getValueNumeric();
                        Double innerQuartile = upperQuartile - lowerQuartile;
                        Double innerQuartileLimit = innerQuartile * 1.5; // outliers will be greater than this from the upper/lower quartile
                        Double upperQuartileLimit = upperQuartile + innerQuartileLimit;
                        Double lowerQuartileLimit = lowerQuartile - innerQuartileLimit;

                        List<Obs> outliers = new Vector<Obs>();

                        // move outliers to the outliers list
                        // removing lower quartile outliers
                        for (i = 0; i < size - xpercentile; i++) {
                            Obs possibleOutlier = numericAnswers.get(i);
                            if (possibleOutlier.getValueNumeric() >= lowerQuartileLimit) {
                                break; // quit if this value is greater than the lower limit
                            }
                            outliers.add(possibleOutlier);
                        }

                        // removing upper quartile outliers
                        for (i = size.intValue() - 1; i >= xpercentile; i--) {
                            Obs possibleOutlier = numericAnswers.get(i);
                            if (possibleOutlier.getValueNumeric() <= upperQuartileLimit) {
                                break; // quit if this value is less than the upper limit
                            }
                            outliers.add(possibleOutlier);
                        }
                        numericAnswers.removeAll(outliers);

                        double[] obsNumericsOutliers = new double[(numericAnswers.size())];
                        i = 0;
                        counts.clear();
                        for (Obs values : numericAnswers) {
                            Double value = values.getValueNumeric();
                            obsNumericsOutliers[i++] = value;
                            Integer count = counts.get(value);
                            counts.put(value, count == null ? 1 : count + 1);
                        }

                        // create outlier histogram chart
                        HistogramDataset outlierHistDataset = new HistogramDataset();
                        outlierHistDataset.addSeries(concept.getName().getName(), obsNumericsOutliers,
                                counts.size());

                        JFreeChart histogramOutliers = ChartFactory.createHistogram(concept.getName().getName(),
                                msa.getMessage("Concept.stats.histogramDomainAxisTitle"),
                                msa.getMessage("Concept.stats.histogramRangeAxisTitle"), outlierHistDataset,
                                PlotOrientation.VERTICAL, false, true, false);
                        map.put("histogramOutliers", histogramOutliers);
                        map.put("outliers", outliers);

                    }

                    // create line graph chart
                    timeDataset.addSeries(timeSeries);
                    JFreeChart lineChart = ChartFactory.createTimeSeriesChart(concept.getName().getName(),
                            msa.getMessage("Concept.stats.lineChartDomainAxisLabel"),
                            msa.getMessage("Concept.stats.lineChartRangeAxisLabel"), timeDataset, false, true,
                            false);
                    map.put("timeSeries", lineChart);

                }
            } else if (ConceptDatatype.BOOLEAN.equals(concept.getDatatype().getHl7Abbreviation())) {
                // create bar chart for boolean answers
                map.put("displayType", "boolean");

                List<Obs> obs = obsService.getObservations(null, null, Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null, null, null, null,
                        null, null, false);

                DefaultPieDataset pieDataset = new DefaultPieDataset();

                // count the number of unique answers
                Map<String, Integer> counts = new HashMap<String, Integer>();
                for (Obs o : obs) {
                    Boolean answer = o.getValueAsBoolean();
                    if (answer == null) {
                        answer = false;
                    }
                    String name = answer.toString();
                    Integer count = counts.get(name);
                    counts.put(name, count == null ? 1 : count + 1);
                }

                // put the counts into the dataset
                for (Map.Entry<String, Integer> entry : counts.entrySet()) {
                    pieDataset.setValue(entry.getKey(), entry.getValue());
                }

                JFreeChart pieChart = ChartFactory.createPieChart(concept.getName().getName(), pieDataset, true,
                        true, false);
                map.put("pieChart", pieChart);

            } else if (ConceptDatatype.CODED.equals(concept.getDatatype().getHl7Abbreviation())) {
                // create pie graph for coded answers
                map.put("displayType", "coded");

                List<Obs> obs = obsService.getObservations(null, null, Collections.singletonList(concept), null,
                        Collections.singletonList(OpenmrsConstants.PERSON_TYPE.PERSON), null, null, null, null,
                        null, null, false);

                DefaultPieDataset pieDataset = new DefaultPieDataset();

                // count the number of unique answers
                Map<String, Integer> counts = new HashMap<String, Integer>();
                for (Obs o : obs) {
                    Concept value = o.getValueCoded();
                    String name;
                    if (value == null) {
                        name = "[value_coded is null]";
                    } else {
                        name = value.getName().getName();
                    }
                    Integer count = counts.get(name);
                    counts.put(name, count == null ? 1 : count + 1);
                }

                // put the counts into the dataset
                for (Map.Entry<String, Integer> entry : counts.entrySet()) {
                    pieDataset.setValue(entry.getKey(), entry.getValue());
                }

                JFreeChart pieChart = ChartFactory.createPieChart(concept.getName().getName(), pieDataset, true,
                        true, false);
                map.put("pieChart", pieChart);

            }
        }

    }

    //map.put("obs", obs);
    //map.put("obsAnswered", obsAnswered);

    map.put("locale", locale.getLanguage().substring(0, 2));

    return map;
}

From source file:playground.anhorni.surprice.analysis.ModeSharesEventHandler.java

public HistogramDataset getHistogramDataset(final int nBins) {
    HistogramDataset output = new HistogramDataset();
    output.setType(HistogramType.RELATIVE_FREQUENCY);
    ArrayList<Double> croppedData = new ArrayList<Double>();

    for (String mode : this.rawData.keySet()) {
        for (double d : this.rawData.get(mode).getElements()) {
            if (d < this.maxXYForPlotting) {
                croppedData.add(d);/*from w w  w.j  a v a  2s . com*/
            }
        }
        output.addSeries(mode, Utils.convert(croppedData), nBins);
    }
    return output;
}

From source file:org.geopublishing.atlasStyler.classification.FeatureClassification.java

@Override
public BufferedImage createHistogramImage(boolean showMean, boolean showSd, int histogramBins,
        String label_xachsis) throws InterruptedException, IOException {
    HistogramDataset hds = new HistogramDataset();
    DoubleArrayList valuesAL;// w  w  w. j  av a 2s . co m
    valuesAL = getStatistics().elements();
    // new double[] {0.4,3,4,2,5.,22.,4.,2.,33.,12.}
    double[] elements = Arrays.copyOf(valuesAL.elements(), getStatistics().size());
    hds.addSeries(1, elements, histogramBins);

    /** Statically label the Y Axis **/
    String label_yachsis = ASUtil.R("QuantitiesClassificationGUI.Histogram.YAxisLabel");

    JFreeChart chart = org.jfree.chart.ChartFactory.createHistogram(null, label_xachsis, label_yachsis, hds,
            PlotOrientation.VERTICAL, false, true, true);

    /***********************************************************************
     * Paint the classes into the JFreeChart
     */
    int countLimits = 0;
    for (Double cLimit : getClassLimits()) {
        ValueMarker marker = new ValueMarker(cLimit);
        XYPlot plot = chart.getXYPlot();
        marker.setPaint(Color.orange);
        marker.setLabel(String.valueOf(countLimits));
        marker.setLabelAnchor(RectangleAnchor.TOP_LEFT);
        marker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        plot.addDomainMarker(marker);

        countLimits++;
    }

    /***********************************************************************
     * Optionally painting SD and MEAN into the histogram
     */
    try {
        if (showSd) {
            ValueMarker marker;
            marker = new ValueMarker(getStatistics().standardDeviation(), Color.green.brighter(),
                    new BasicStroke(1.5f));
            XYPlot plot = chart.getXYPlot();
            marker.setLabel(ASUtil.R("QuantitiesClassificationGUI.Histogram.SD.ShortLabel"));
            marker.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT);
            marker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
            plot.addDomainMarker(marker);
        }

        if (showMean) {
            ValueMarker marker;
            marker = new ValueMarker(getStatistics().mean(), Color.green.darker(), new BasicStroke(1.5f));
            XYPlot plot = chart.getXYPlot();
            marker.setLabel(ASUtil.R("QuantitiesClassificationGUI.Histogram.Mean.ShortLabel"));
            marker.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT);
            marker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
            plot.addDomainMarker(marker);
        }

    } catch (Exception e) {
        LOGGER.error("Painting SD and MEAN into the histogram", e);
    }

    /***********************************************************************
     * Render the Chart
     */
    BufferedImage image = chart.createBufferedImage(400, 200);

    return image;
}

From source file:baocaoxla.xuly_compare.java

public ChartPanel displayhistogram(BufferedImage image) {

    HistogramDataset dataset = new HistogramDataset();

    final int w = image.getWidth();
    final int h = image.getHeight();
    double[] r = new double[w * h];
    double[] g = new double[w * h];
    double[] b = new double[w * h];
    int dem = 0;/*from w  ww  .j a va 2s .  co m*/
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            Color c = new Color(image.getRGB(j, i));
            r[dem] = c.getRed();
            g[dem] = c.getGreen();
            b[dem] = c.getBlue();
            dem++;
        }
    }
    //r = raster.getSamples(0, 0, w, h, 0, r);
    dataset.addSeries("Red", r, 256);
    //r = raster.getSamples(0, 0, w, h, 1, r);
    dataset.addSeries("Green", g, 256);
    // r = raster.getSamples(0, 0, w, h, 2, r);
    dataset.addSeries("Blue", b, 256);
    // chart
    JFreeChart chart = ChartFactory.createHistogram("Histogram", "Value", "Count", dataset,
            PlotOrientation.VERTICAL, true, true, false);
    ChartPanel panel = new ChartPanel(chart);
    return panel;

}

From source file:org.neuroph.netbeans.main.DataSetStatTopComponent.java

/**
 * Returns data set for give column index.
 *
 * @return Dataset for give column index.
 *//*from  ww w . j  a v a  2 s .c  o  m*/
private HistogramDataset createHistogramDataSet() {
    int columnIndex = Integer.parseInt(columnsComboBox.getSelectedItem().toString());
    int binsCount = Integer.parseInt(histogramBinsComboBox.getSelectedItem().toString());
    HistogramDataset chartDataset = new HistogramDataset();
    DataSet dataSet = statistics.getDataSet();
    int rowCount = dataSet.getRows().size();
    double[] values = new double[rowCount];

    for (int i = 0; i < rowCount; i++) {
        double[] row = dataSet.getRowAt(i).toArray();
        values[i] = row[columnIndex];
    }

    chartDataset.addSeries(dataSet.getColumnName(columnIndex), values, binsCount);
    return chartDataset;
}

From source file:com.rapidminer.gui.viewer.metadata.model.NumericalAttributeStatisticsModel.java

/**
 * Creates a {@link HistogramDataset} for this {@link Attribute}.
 *
 * @param exampleSet/*  w  w w  . j  a v  a2s. c  om*/
 * @return
 */
private HistogramDataset createHistogramDataset(ExampleSet exampleSet) {
    HistogramDataset dataset = new HistogramDataset();

    double[] array = new double[exampleSet.size()];
    int count = 0;

    for (Example example : exampleSet) {
        double value = example.getDataRow().get(getAttribute());
        // don't use missing values because otherwise JFreeChart tries to plot them too which
        // can lead to false histograms
        if (!Double.isNaN(value)) {
            array[count++] = value;
        }
    }

    // add points to data set (if any)
    if (count > 0) {
        // truncate array if necessary
        if (count < array.length) {
            array = Arrays.copyOf(array, count);
        }
        dataset.addSeries(getAttribute().getName(), array, Math.min(array.length, MAX_BINS_HISTOGRAM));
    }

    return dataset;
}

From source file:playground.christoph.evacuation.analysis.EvacuationTimePictureWriter.java

private JFreeChart createHistogramChart(String transportMode, double[] travelTimes) {

    HistogramDataset dataset = new HistogramDataset();
    dataset.setType(HistogramType.RELATIVE_FREQUENCY);
    dataset.addSeries("evacuation travel time " + transportMode, travelTimes, 20);

    JFreeChart chart = ChartFactory.createHistogram(null, null, "frequency", dataset, PlotOrientation.VERTICAL,
            true, false, false);/*from   w ww. j a  va2  s  . c  om*/
    chart.getXYPlot().setForegroundAlpha(0.75f);

    /*
     * set x-axis range 
     */
    double min = 0.0;
    double max = maxEvacuationTime;
    if (limitMaxEvacuationTime) {
        double cutOffValue = meanEvacuationTime + standardDeviation * evacuationTimeCutOffFactor;
        max = cutOffValue;
    }
    chart.getXYPlot().getDomainAxis().setLowerBound(min);
    chart.getXYPlot().getDomainAxis().setUpperBound(max);

    return chart;
}

From source file:OAT.trading.thread.BacktestThread.java

private void showHistogram(String title, double[] data) {
    if (data == null || data.length == 0) {
        return;/*from   ww w  . j av  a  2  s  .  c  om*/
    }

    HistogramDataset histogramDataset = new HistogramDataset();
    histogramDataset.addSeries(title, data, 15);

    JFreeChart chart = ChartFactory.createHistogram("", "", "", histogramDataset, PlotOrientation.VERTICAL,
            false, false, false);

    new BasicChartFrame(title, chart).setVisible(true);
}

From source file:org.fhcrc.cpl.viewer.amt.commandline.AmtDatabaseDiagnosticCommandLineModule.java

/**
 * Histogram all masses in the database/* w  w  w  .  j  av  a2 s. c  o m*/
 * @return
 */
protected JFreeChart histogramMasses() {
    HistogramDataset dataset = new HistogramDataset();

    double[] histData = new double[amtDB.numEntries()];

    AmtPeptideEntry[] entries = amtDB.getEntries();
    for (int i = 0; i < amtDB.numEntries(); i++) {
        histData[i] = entries[i].getMass();

    }
    dataset.addSeries("masses", histData, 500);

    JFreeChart chart = ChartFactory.createHistogram("masses", "masses", "masses", dataset,
            PlotOrientation.VERTICAL, false, false, false);
    ChartDialog cd2 = new ChartDialog(chart);
    cd2.setSize(800, 600);
    PanelWithChart pwc = new PanelWithChart(chart);

    pwc.setName("masses");

    if (showCharts)
        pwc.displayInTab();
    return pwc.getChart();
}