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

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

Introduction

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

Prototype

public HistogramDataset() 

Source Link

Document

Creates a new (empty) dataset with a default type of HistogramType .FREQUENCY.

Usage

From source file:org.jfree.data.statistics.HistogramDatasetTest.java

/**
 * This test is derived from a reported bug.
 *//* w w  w .  java 2  s. c  o  m*/
@Test
public void testBinBoundaries() {
    double[] values = { -5.000000000000286E-5 };
    int bins = 1260;
    double minimum = -0.06307522528160199;
    double maximum = 0.06297522528160199;
    HistogramDataset d = new HistogramDataset();
    d.addSeries("S1", values, bins, minimum, maximum);
    assertEquals(0.0, d.getYValue(0, 629), EPSILON);
    assertEquals(1.0, d.getYValue(0, 630), EPSILON);
    assertEquals(0.0, d.getYValue(0, 631), EPSILON);
    assertTrue(values[0] > d.getStartXValue(0, 630));
    assertTrue(values[0] < d.getEndXValue(0, 630));
}

From source file:org.jfree.data.statistics.HistogramDatasetTest.java

/**
 * Some checks for bug 1553088.  An IndexOutOfBoundsException is thrown
 * when a data value is *very* close to the upper limit of the last bin.
 *//*from  w w  w . j  a  v a2s  .  co m*/
@Test
public void test1553088() {
    double[] values = { -1.0, 0.0, -Double.MIN_VALUE, 3.0 };
    HistogramDataset d = new HistogramDataset();
    d.addSeries("S1", values, 2, -1.0, 0.0);
    assertEquals(-1.0, d.getStartXValue(0, 0), EPSILON);
    assertEquals(-0.5, d.getEndXValue(0, 0), EPSILON);
    assertEquals(1.0, d.getYValue(0, 0), EPSILON);

    assertEquals(-0.5, d.getStartXValue(0, 1), EPSILON);
    assertEquals(0.0, d.getEndXValue(0, 1), EPSILON);
    assertEquals(3.0, d.getYValue(0, 1), EPSILON);
}

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

/**
 * Creates a {@link HistogramDataset} for this {@link Attribute}.
 *
 * @param exampleSet/*w w w.java2  s .c  om*/
 * @return
 */
private HistogramDataset createHistogramDataset(final 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:v800_trainer.JHistogram.java

public JPanel StartHistoSp(JCicloTronic JTronicHandle) {

    boolean Summenhisto;
    int von = 0;//from   w  w w  .j  a  v  a 2 s  .  co 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("", "Geschwindigkeit [km/h]", "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("HistovonSp", "100"));
        bis = Integer.parseInt(JTronicHandle.Properties.getProperty("HistobisSp", "200"));
        Gruppen = Integer.parseInt(JTronicHandle.Properties.getProperty("HistostepSp", "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].Geschw_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].Geschw_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: Sp " + 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:fr.ens.transcriptome.corsen.gui.qt.ResultGraphs.java

/**
 * Create a histogram of distance distribution.
 * @param results Result to use/*ww  w.  j a va 2s .c  o m*/
 * @return a QImage of the graph
 */
public QImage createDistanceDistributionImage(final CorsenResult results, final int classes,
        final String unit) {

    HistogramDataset histogramdataset = new HistogramDataset();

    createHistoDataSet(results.getMinDistances(), "Min distances", histogramdataset, classes);
    // createHistoDataSet(results.getMaxDistances(), "Max distances",
    // histogramdataset);

    JFreeChart chart = ChartFactory.createHistogram("Distribution of minimal distances",
            // title
            "Distance" + unitLegend(unit), // domain axis label
            "Intensity", // range axis label
            histogramdataset, // data

            PlotOrientation.VERTICAL, // orientation
            false, // include legend
            true, // tooltips?
            false // URLs?
    );

    addTransparency(chart);

    final BufferedImage image = chart.createBufferedImage(this.width, this.height, BufferedImage.TYPE_INT_ARGB,
            null);

    return new QImage(toByte(image.getData().getDataBuffer()), this.width, this.height,
            QImage.Format.Format_ARGB32);
}

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)
 *//* w  w w  .j av a  2 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:org.jfree.data.statistics.HistogramDatasetTest.java

/**
 * A test to show the limitation addressed by patch 2902842.
 *//*from  w  w w .ja  v  a2s  .c o m*/
@Test
public void test2902842() {
    this.lastEvent = null;
    double[] values = { 0.0, 1.0, 2.0, 3.0, 4.0, 5.0 };
    HistogramDataset hd = new HistogramDataset();
    hd.addChangeListener(this);
    hd.addSeries("S1", values, 5);
    assertNotNull(this.lastEvent);
}

From source file:org.ect.reo.simulation.views.SimulationViewResults.java

private static JFreeChart createHistogram(Statistic statistic, Composite composite) {
    HistogramDataset dataset = new HistogramDataset();
    dataset.setType(HistogramType.RELATIVE_FREQUENCY);
    int numOfBatches = Integer.parseInt(SimulationViewOptions.batchNumberText.getText());
    double[] values = new double[numOfBatches];

    for (int i = 0; i < numOfBatches; i++) {
        values[i] = statistic.getStatisticValue(i);
    }//  w  ww  .ja  v a 2 s  . c o  m

    try {
        dataset.addSeries("Histogram of batch values", values,
                (int) Math.ceil(Math.log(numOfBatches) / Math.log(2) + 1));
        return ChartFactory.createHistogram("Batch results", "Value", "Relative frequency", dataset,
                PlotOrientation.VERTICAL, false, true, false);
    } catch (Throwable t) {
        return null;
    }
}

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 va  2  s.com*/
            }
        }
        output.addSeries(mode, Utils.convert(croppedData), nBins);
    }
    return output;
}

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

/**
 *
 * @param track/*from  w  w  w  .jav  a 2 s  .  com*/
 */
private void plotDeltaX(Track track) {
    Double[] deltaXValues = ComputationUtils.transpose2DArray(track.getSteps())[0];
    double[] values = ArrayUtils.toPrimitive(ComputationUtils.excludeNullValues(deltaXValues));
    HistogramDataset histogramDataset = new HistogramDataset();
    histogramDataset.addSeries("", values, 2);
    String title = "delta_x_values for track: " + track.getTrackid();
    JFreeChart jFreeChart = ChartFactory.createHistogram(title, "delta_x", "count", histogramDataset,
            PlotOrientation.VERTICAL, true, true, true);
    ChartPanel chartPanel = new ChartPanel(jFreeChart);
    computationDataPanel.getDeltaxPlotPanel().removeAll();
    computationDataPanel.getDeltaxPlotPanel().add(chartPanel, gridBagConstraints);
    computationDataPanel.getDeltaxPlotPanel().revalidate();
    computationDataPanel.getDeltaxPlotPanel().repaint();
}