Example usage for org.jfree.data DataUtilities getCumulativePercentages

List of usage examples for org.jfree.data DataUtilities getCumulativePercentages

Introduction

In this page you can find the example usage for org.jfree.data DataUtilities getCumulativePercentages.

Prototype

public static KeyedValues getCumulativePercentages(KeyedValues data) 

Source Link

Document

Returns a KeyedValues instance that contains the cumulative percentage values for the data in another KeyedValues instance.

Usage

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

public static CategoryDataset[] createDatasets() {
    DefaultKeyedValues defaultkeyedvalues = new DefaultKeyedValues();
    defaultkeyedvalues.addValue("C", new Integer(4843));
    defaultkeyedvalues.addValue("C++", new Integer(2098));
    defaultkeyedvalues.addValue("C#", new Integer(26));
    defaultkeyedvalues.addValue("Java", new Integer(1901));
    defaultkeyedvalues.addValue("Perl", new Integer(2507));
    defaultkeyedvalues.addValue("PHP", new Integer(1689));
    defaultkeyedvalues.addValue("Python", new Integer(948));
    defaultkeyedvalues.addValue("Ruby", new Integer(100));
    defaultkeyedvalues.addValue("SQL", new Integer(263));
    defaultkeyedvalues.addValue("Unix Shell", new Integer(485));
    defaultkeyedvalues.sortByValues(SortOrder.DESCENDING);
    org.jfree.data.KeyedValues keyedvalues = DataUtilities.getCumulativePercentages(defaultkeyedvalues);
    CategoryDataset categorydataset = DatasetUtilities.createCategoryDataset("Languages", defaultkeyedvalues);
    CategoryDataset categorydataset1 = DatasetUtilities.createCategoryDataset("Cumulative", keyedvalues);
    return (new CategoryDataset[] { categorydataset, categorydataset1 });
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.others.CumulativeCurveChart.java

public DatasetMap calculateValue() throws Exception {

    logger.debug("IN");
    String res = DataSetAccessFunctions.getDataSetResultFromId(profile, getData(), parametersObject);

    SourceBean sbRows = SourceBean.fromXMLString(res);
    SourceBean sbRow = (SourceBean) sbRows.getAttribute("ROW");
    List listAtts = sbRow.getContainedAttributes();

    DefaultKeyedValues keyedValues = new DefaultKeyedValues();

    for (Iterator iterator = listAtts.iterator(); iterator.hasNext();) {
        SourceBeanAttribute att = (SourceBeanAttribute) iterator.next();
        String name = att.getKey();
        String valueS = (String) att.getValue();

        //try Double and Integer Conversion

        Double valueD = null;/* w  w w  .  jav  a 2  s. c o  m*/
        try {
            valueD = Double.valueOf(valueS);
        } catch (Exception e) {
        }

        Integer valueI = null;
        if (valueD == null) {
            valueI = Integer.valueOf(valueS);
        }

        if (name != null && valueD != null) {
            keyedValues.addValue(name, valueD);
        } else if (name != null && valueI != null) {
            keyedValues.addValue(name, valueI);
        }
    }
    keyedValues.sortByValues(sortOrder); //let user choose

    KeyedValues cumulative = DataUtilities.getCumulativePercentages(keyedValues);

    CategoryDataset dataset = DatasetUtilities.createCategoryDataset("Languages", keyedValues);
    CategoryDataset dataset2 = DatasetUtilities.createCategoryDataset("Cumulative", cumulative);

    logger.debug("OUT");
    DatasetMap datasets = new DatasetMap();
    datasets.addDataset("1", dataset);
    datasets.addDataset("2", dataset2);

    return datasets;

}

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

/**
 * Creates a new demo instance./* w  w  w  .j  a  v  a  2s.  com*/
 *
 * @param title  the frame title.
 */
public ParetoChartDemo(final String title) {

    super(title);

    final DefaultKeyedValues data = new DefaultKeyedValues();
    data.addValue("C", new Integer(4843));
    data.addValue("C++", new Integer(2098));
    data.addValue("C#", new Integer(26));
    data.addValue("Java", new Integer(1901));
    data.addValue("Perl", new Integer(2507));
    data.addValue("PHP", new Integer(1689));
    data.addValue("Python", new Integer(948));
    data.addValue("Ruby", new Integer(100));
    data.addValue("SQL", new Integer(263));
    data.addValue("Unix Shell", new Integer(485));

    data.sortByValues(SortOrder.DESCENDING);
    final KeyedValues cumulative = DataUtilities.getCumulativePercentages(data);
    final CategoryDataset dataset = DatasetUtilities.createCategoryDataset("Languages", data);

    // create the chart...
    final JFreeChart chart = ChartFactory.createBarChart("Freshmeat Software Projects", // chart title
            "Language", // domain axis label
            "Projects", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, true, // include legend
            true, false);

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
    chart.addSubtitle(new TextTitle("By Programming Language"));
    chart.addSubtitle(new TextTitle("As at 5 March 2003"));

    // set the background color for the chart...
    chart.setBackgroundPaint(new Color(0xBBBBDD));

    // get a reference to the plot for further customisation...
    final CategoryPlot plot = chart.getCategoryPlot();

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

    // set the range axis to display integers only...
    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    final LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();

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

    plot.setDatasetRenderingOrder(DatasetRenderingOrder.REVERSE);
    // OPTIONAL CUSTOMISATION COMPLETED.

    // add the chart to a panel...
    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(550, 270));
    setContentPane(chartPanel);

}

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.
 * /* ww w  . ja v a2s.  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:com.rapidminer.gui.plotter.charts.ParetoChartPlotter.java

private JFreeChart createChart() {
    if (data.getItemCount() > 0) {
        // get cumulative percentages
        KeyedValues cumulative = DataUtilities.getCumulativePercentages(data);

        CategoryDataset categoryDataset = DatasetUtilities.createCategoryDataset(
                "Count for " + this.dataTable.getColumnName(this.countColumn) + " = " + countValue, data);

        // create the chart...
        final JFreeChart chart = ChartFactory.createBarChart(null, // chart title
                this.dataTable.getColumnName(this.groupByColumn), // domain axis label
                "Count", // range axis label
                categoryDataset, // data
                PlotOrientation.VERTICAL, true, // include legend
                true, false);//w w w.  j av a2s.c om

        // set the background color for the chart...
        chart.setBackgroundPaint(Color.WHITE);

        // get a reference to the plot for further customization...
        CategoryPlot plot = chart.getCategoryPlot();

        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setLowerMargin(0.02);
        domainAxis.setUpperMargin(0.02);
        domainAxis.setLabelFont(LABEL_FONT_BOLD);
        domainAxis.setTickLabelFont(LABEL_FONT);

        // set the range axis to display integers only...
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits(Locale.US));
        rangeAxis.setLabelFont(LABEL_FONT_BOLD);
        rangeAxis.setTickLabelFont(LABEL_FONT);

        // second data set (cumulative percentages)
        CategoryDataset dataset2 = DatasetUtilities.createCategoryDataset("Cumulative (Percent)", cumulative);

        LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();
        renderer2.setSeriesPaint(0, SwingTools.VERY_DARK_BLUE.darker());

        NumberAxis axis2 = new NumberAxis("Percent of " + countValue);
        axis2.setNumberFormatOverride(NumberFormat.getPercentInstance());
        axis2.setLabelFont(LABEL_FONT_BOLD);
        axis2.setTickLabelFont(LABEL_FONT);

        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, dataset2);
        plot.setRenderer(1, renderer2);
        plot.mapDatasetToRangeAxis(1, 1);

        axis2.setTickUnit(new NumberTickUnit(0.1));

        // show grid lines
        plot.setRangeGridlinesVisible(true);

        // bring cumulative line to front
        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

        if (isLabelRotating()) {
            domainAxis.setTickLabelsVisible(true);
            domainAxis.setCategoryLabelPositions(
                    CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 2.0d));
        }

        return chart;
    } else {
        return null;
    }
}

From source file:ca.myewb.frame.servlet.GraphServlet.java

private JFreeChart getChapterPareto(DefaultKeyedValues data, String title, String quantity, String range) {

    JFreeChart chart;/*from   w  w w. java  2  s. c o  m*/

    data.sortByValues(SortOrder.DESCENDING);
    KeyedValues cummulative = DataUtilities.getCumulativePercentages(data);
    CategoryDataset dataset = DatasetUtilities.createCategoryDataset(quantity, data);

    // create the chart...
    chart = ChartFactory.createBarChart(title, // chart title
            "Chapter", // domain axis label
            range, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, true, // include legend
            true, false);

    CategoryPlot plot = chart.getCategoryPlot();

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setLowerMargin(0.02);
    domainAxis.setUpperMargin(0.02);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

    // set the range axis to display integers only...
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();

    CategoryDataset dataset2 = DatasetUtilities.createCategoryDataset("Cummulative", cummulative);
    NumberAxis axis2 = new NumberAxis("Percent");
    axis2.setNumberFormatOverride(NumberFormat.getPercentInstance());
    axis2.setUpperBound(1);
    axis2.setLowerBound(0);
    plot.setRangeAxis(1, axis2);
    plot.setDataset(1, dataset2);
    plot.setRenderer(1, renderer2);
    plot.mapDatasetToRangeAxis(1, 1);
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

    return chart;
}