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

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

Introduction

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

Prototype

public DefaultMultiValueCategoryDataset() 

Source Link

Document

Creates a new dataset.

Usage

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

/**
 * Confirm that cloning works.//from w ww .ja va  2s.  c o m
 */
@Test
public void testCloning() throws CloneNotSupportedException {
    DefaultMultiValueCategoryDataset d1 = new DefaultMultiValueCategoryDataset();
    DefaultMultiValueCategoryDataset d2 = (DefaultMultiValueCategoryDataset) d1.clone();
    assertTrue(d1 != d2);
    assertTrue(d1.getClass() == d2.getClass());
    assertTrue(d1.equals(d2));

    // try a dataset with some content...
    List values = new ArrayList();
    values.add(new Integer(99));
    d1.add(values, "R1", "C1");
    d2 = (DefaultMultiValueCategoryDataset) d1.clone();
    assertTrue(d1 != d2);
    assertTrue(d1.getClass() == d2.getClass());
    assertTrue(d1.equals(d2));

    // check that the clone doesn't share the same underlying arrays.
    List values2 = new ArrayList();
    values2.add(new Integer(111));
    d1.add(values2, "R2", "C2");
    assertFalse(d1.equals(d2));
    d2.add(values2, "R2", "C2");
    assertTrue(d1.equals(d2));
}

From source file:org.jax.pubarray.server.restful.GraphingResource.java

/**
 * Create a graph for the given configuration
 * @param graphConfiguration//from   ww  w .  ja  v a2 s. c o  m
 *          the key
 * @return
 *          the graph
 */
@SuppressWarnings("unchecked")
private JFreeChart createProbeIntensityGraph(ProbeIntensityGraphConfiguration graphConfiguration) {
    try {
        Connection connection = this.getConnection();

        String[] probeIds = graphConfiguration.getProbeIds();
        double[][] probeDataRows = new double[probeIds.length][];
        for (int i = 0; i < probeIds.length; i++) {
            probeDataRows[i] = this.persistenceManager.getDataRowForProbeID(connection, probeIds[i]);
        }

        TableColumnMetadata orderBy = graphConfiguration.getOrderProbesBy();
        final List<Comparable> orderByItems;
        if (orderBy != null) {
            LOG.info("We are ordering by: " + orderBy);
            orderByItems = this.persistenceManager.getDesignDataColumn(connection, orderBy);
        } else {
            orderByItems = null;
        }

        TableMetadata metadata = this.persistenceManager.getDataTableMetadata(connection);
        final CategoryDataset categoryDataset;
        if (graphConfiguration.getGroupReplicates()) {
            switch (graphConfiguration.getGroupedGraphType()) {
            case BOX_PLOT: {
                categoryDataset = new DefaultBoxAndWhiskerCategoryDataset();
            }
                break;

            case SCATTER_PLOT: {
                categoryDataset = new DefaultMultiValueCategoryDataset();
            }
                break;

            default:
                throw new IllegalArgumentException(
                        "don't know how to deal with plot type: " + graphConfiguration.getGroupedGraphType());
            }
        } else {
            categoryDataset = new DefaultCategoryDataset();
        }

        // iterate through all of the selected probesets
        List<QualifiedColumnMetadata> termsOfInterest = Arrays.asList(graphConfiguration.getTermsOfInterest());
        for (int rowIndex = 0; rowIndex < probeDataRows.length; rowIndex++) {
            double[] currRow = probeDataRows[rowIndex];
            assert currRow.length == metadata.getColumnMetadata().length - 1;

            // should we log2 transform the data?
            if (graphConfiguration.getLog2TransformData()) {
                for (int i = 0; i < currRow.length; i++) {
                    currRow[i] = Math.log(currRow[i]) / LOG2_FACTOR;
                }
            }

            // iterate through the columns in the data table (each column
            // represents a different array)
            List<ComparableContainer<Double, Comparable>> rowElemList = new ArrayList<ComparableContainer<Double, Comparable>>();
            for (int colIndex = 0; colIndex < currRow.length; colIndex++) {
                // we use +1 indexing here because we want to skip over
                // the probesetId metadata and get right to the
                // array intensity metadata
                TableColumnMetadata colMeta = metadata.getColumnMetadata()[colIndex + 1];

                // check to see if we need to skip this data
                if (!graphConfiguration.getIncludeDataFromAllArrays()) {
                    // if it's one of the "terms of interest" we will keep
                    // it. we're using a brute force search here
                    boolean keepThisOne = false;
                    for (QualifiedColumnMetadata termOfInterest : termsOfInterest) {
                        if (termOfInterest.getTableName().equals(metadata.getTableName())
                                && termOfInterest.getName().equals(colMeta.getName())) {
                            keepThisOne = true;
                            break;
                        }
                    }

                    if (!keepThisOne) {
                        continue;
                    }
                }

                final String columnName = colMeta.getName();
                final Comparable columnKey;
                if (orderByItems == null) {
                    columnKey = columnName;
                } else {
                    // the ordering will be done on the selected
                    // "order by" design criteria
                    columnKey = new ComparableContainer<String, Comparable>(columnName,
                            orderByItems.get(colIndex), !graphConfiguration.getGroupReplicates());

                    // TODO remove me!!!!
                    System.out.println("For array " + columnName + " the order by " + "value is: "
                            + orderByItems.get(colIndex));
                    // end of remove me
                }

                rowElemList
                        .add(new ComparableContainer<Double, Comparable>(currRow[colIndex], columnKey, false));
            }

            Collections.sort(rowElemList);

            if (graphConfiguration.getGroupReplicates()) {
                switch (graphConfiguration.getGroupedGraphType()) {
                case BOX_PLOT: {
                    DefaultBoxAndWhiskerCategoryDataset dataset = (DefaultBoxAndWhiskerCategoryDataset) categoryDataset;
                    for (int i = 0; i < rowElemList.size(); i++) {
                        List<Double> groupList = new ArrayList<Double>();
                        groupList.add(rowElemList.get(i).getElement());
                        Comparable colKey = rowElemList.get(i).getComparable();

                        i++;
                        for (; i < rowElemList.size()
                                && rowElemList.get(i).getComparable().equals(colKey); i++) {
                            groupList.add(rowElemList.get(i).getElement());
                        }
                        i--;

                        dataset.add(groupList, probeIds[rowIndex], colKey);
                    }
                }
                    break;

                case SCATTER_PLOT: {
                    DefaultMultiValueCategoryDataset dataset = (DefaultMultiValueCategoryDataset) categoryDataset;
                    for (int i = 0; i < rowElemList.size(); i++) {
                        List<Double> groupList = new ArrayList<Double>();
                        groupList.add(rowElemList.get(i).getElement());
                        Comparable colKey = rowElemList.get(i).getComparable();

                        i++;
                        for (; i < rowElemList.size()
                                && rowElemList.get(i).getComparable().equals(colKey); i++) {
                            groupList.add(rowElemList.get(i).getElement());
                        }
                        i--;

                        dataset.add(groupList, probeIds[rowIndex], colKey);
                    }
                }
                    break;
                }
            } else {
                DefaultCategoryDataset dataset = (DefaultCategoryDataset) categoryDataset;
                for (ComparableContainer<Double, Comparable> rowElem : rowElemList) {
                    dataset.addValue(rowElem.getElement(), probeIds[rowIndex], rowElem.getComparable());
                }
            }
        }

        CategoryAxis xAxis = new CategoryAxis();
        if (graphConfiguration.getGroupReplicates() && orderBy != null) {
            xAxis.setLabel(orderBy.getName());
        } else {
            if (orderBy != null) {
                xAxis.setLabel("Arrays (Ordered By " + orderBy.getName() + ")");
            } else {
                xAxis.setLabel("Arrays");
            }
        }
        xAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);

        final NumberAxis yAxis;
        if (graphConfiguration.getLog2TransformData()) {
            yAxis = new NumberAxis("log2(Intensity)");
        } else {
            yAxis = new NumberAxis("Intensity");
        }
        yAxis.setAutoRange(true);
        yAxis.setAutoRangeIncludesZero(false);

        // TODO: this is a HACK to deal with auto-range bug in JFreeChart
        //       which occurs when doing the grouped scatter plot
        if (graphConfiguration.getGroupReplicates()
                && graphConfiguration.getGroupedGraphType() == GroupedGraphType.SCATTER_PLOT) {
            double minVal = Double.POSITIVE_INFINITY;
            double maxVal = Double.NEGATIVE_INFINITY;
            for (double[] dataRow : probeDataRows) {
                for (double datum : dataRow) {
                    if (datum > maxVal) {
                        maxVal = datum;
                    }

                    if (datum < minVal) {
                        minVal = datum;
                    }
                }

                if (minVal != Double.POSITIVE_INFINITY && maxVal != Double.NEGATIVE_INFINITY
                        && minVal != maxVal) {
                    yAxis.setAutoRange(false);

                    double margin = (maxVal - minVal) * 0.02;
                    Range yRange = new Range(minVal - margin, maxVal + margin);
                    yAxis.setRange(yRange);
                }
            }
        }
        // END HACK

        final CategoryItemRenderer renderer;
        if (graphConfiguration.getGroupReplicates()) {
            switch (graphConfiguration.getGroupedGraphType()) {
            case BOX_PLOT: {
                BoxAndWhiskerRenderer boxRenderer = new BoxAndWhiskerRenderer();
                boxRenderer.setMaximumBarWidth(0.03);
                renderer = boxRenderer;
            }
                break;

            case SCATTER_PLOT: {
                renderer = new ScatterRenderer();
            }
                break;

            default:
                throw new IllegalArgumentException(
                        "don't know how to deal with plot type: " + graphConfiguration.getGroupedGraphType());
            }
        } else {
            renderer = new LineAndShapeRenderer();
        }
        Plot plot = new CategoryPlot(categoryDataset, xAxis, yAxis, renderer);

        return new JFreeChart("Intensity Values", plot);
    } catch (SQLException ex) {
        LOG.log(Level.SEVERE, "failed to generate image", ex);
        return null;
    }
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java

private boolean writeDetailedFactorAnalysis(ExpressionExperiment ee, OutputStream os) throws Exception {
    SVDValueObject svdo = svdService.getSvdFactorAnalysis(ee.getId());
    if (svdo == null)
        return false;

    if (svdo.getFactors().isEmpty() && svdo.getDates().isEmpty()) {
        return false;
    }//from ww w.  ja  va  2  s.  c o m
    Map<Integer, Map<Long, Double>> factorCorrelations = svdo.getFactorCorrelations();
    // Map<Integer, Map<Long, Double>> factorPvalues = svdo.getFactorPvalues();
    Map<Integer, Double> dateCorrelations = svdo.getDateCorrelations();

    assert ee.getId().equals(svdo.getId());

    ee = expressionExperimentService.thawLite(ee); // need the experimental design
    int maxWidth = 30;
    Map<Long, String> efs = this.getFactorNames(ee, maxWidth);
    Map<Long, ExperimentalFactor> efIdMap = EntityUtils
            .getIdMap(ee.getExperimentalDesign().getExperimentalFactors());
    Collection<Long> continuousFactors = new HashSet<>();
    for (ExperimentalFactor ef : ee.getExperimentalDesign().getExperimentalFactors()) {
        boolean isContinous = ExperimentalDesignUtils.isContinuous(ef);
        if (isContinous) {
            continuousFactors.add(ef.getId());
        }
    }

    /*
     * Make plots of the dates vs. PCs, factors vs. PCs.
     */
    int MAX_COMP = 3;

    Map<Long, List<JFreeChart>> charts = new LinkedHashMap<>();
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    /*
     * FACTORS
     */
    String componentShorthand = "PC";
    for (Integer component : factorCorrelations.keySet()) {

        if (component >= MAX_COMP)
            break;
        String xaxisLabel = componentShorthand + (component + 1);

        for (Long efId : factorCorrelations.get(component).keySet()) {

            /*
             * Should not happen.
             */
            if (!efs.containsKey(efId)) {
                log.warn("No experimental factor with id " + efId);
                continue;
            }

            if (!svdo.getFactors().containsKey(efId)) {
                // this should not happen.
                continue;
            }

            boolean isCategorical = !continuousFactors.contains(efId);

            Map<Long, String> categories = new HashMap<>();

            if (isCategorical) {
                this.getCategories(efIdMap, efId, categories);
            }

            if (!charts.containsKey(efId)) {
                charts.put(efId, new ArrayList<JFreeChart>());
            }

            Double a = factorCorrelations.get(component).get(efId);
            String plotname = (efs.get(efId) == null ? "?" : efs.get(efId)) + " " + xaxisLabel; // unique?

            if (a != null && !Double.isNaN(a)) {
                String title = plotname + " " + String.format("%.2f", a);
                List<Double> values = svdo.getFactors().get(efId);
                Double[] eigenGene = this.getEigenGene(svdo, component);
                assert values.size() == eigenGene.length;

                /*
                 * Plot eigengene vs values, add correlation to the plot
                 */
                JFreeChart chart;
                if (isCategorical) {

                    /*
                     * Categorical factor
                     */

                    // use the absolute value of the correlation, since direction is arbitrary.
                    title = plotname + " " + String.format("r=%.2f", Math.abs(a));

                    DefaultMultiValueCategoryDataset dataset = new DefaultMultiValueCategoryDataset();

                    /*
                     * What this code does is organize the factor values by the groups.
                     */
                    Map<String, List<Double>> groupedValues = new TreeMap<>();
                    for (int i = 0; i < values.size(); i++) {
                        Long fvId = values.get(i).longValue();
                        String fvValue = categories.get(fvId);
                        if (fvValue == null) {
                            /*
                             * Problem ...eg gill2006fateinocean id=1748 -- missing values. We just don't plot
                             * anything for this sample.
                             */
                            continue; // is this all we need to do?
                        }
                        if (!groupedValues.containsKey(fvValue)) {
                            groupedValues.put(fvValue, new ArrayList<Double>());
                        }

                        groupedValues.get(fvValue).add(eigenGene[i]);

                        if (log.isDebugEnabled())
                            log.debug(fvValue + " " + values.get(i));
                    }

                    for (String key : groupedValues.keySet()) {
                        dataset.add(groupedValues.get(key), plotname, key);
                    }

                    // don't show the name of the X axis: it's redundant with the title.
                    NumberAxis rangeAxis = new NumberAxis(xaxisLabel);
                    rangeAxis.setAutoRangeIncludesZero(false);
                    // rangeAxis.setAutoRange( false );
                    rangeAxis.setAutoRangeMinimumSize(4.0);
                    // rangeAxis.setRange( new Range( -2, 2 ) );

                    CategoryPlot plot = new CategoryPlot(dataset, new CategoryAxis(null), rangeAxis,
                            new ScatterRenderer());
                    plot.setRangeGridlinesVisible(false);
                    plot.setDomainGridlinesVisible(false);

                    chart = new JFreeChart(title, new Font("SansSerif", Font.BOLD, 12), plot, false);

                    ScatterRenderer renderer = (ScatterRenderer) plot.getRenderer();
                    float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP);
                    renderer.setSeriesFillPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f));
                    renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3));
                    renderer.setUseOutlinePaint(false);
                    renderer.setUseFillPaint(true);
                    renderer.setBaseFillPaint(Color.white);
                    CategoryAxis domainAxis = plot.getDomainAxis();
                    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
                } else {

                    /*
                     * Continuous value factor
                     */

                    DefaultXYDataset series = new DefaultXYDataset();
                    series.addSeries(plotname,
                            new double[][] { ArrayUtils.toPrimitive(values.toArray(new Double[] {})),
                                    ArrayUtils.toPrimitive(eigenGene) });

                    // don't show x-axis label, which would otherwise be efs.get( efId )
                    chart = ChartFactory.createScatterPlot(title, null, xaxisLabel, series,
                            PlotOrientation.VERTICAL, false, false, false);
                    XYPlot plot = chart.getXYPlot();
                    plot.setRangeGridlinesVisible(false);
                    plot.setDomainGridlinesVisible(false);

                    XYItemRenderer renderer = plot.getRenderer();
                    renderer.setBasePaint(Color.white);
                    renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3));
                    float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP);
                    renderer.setSeriesPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f));
                    plot.setRenderer(renderer);
                }

                chart.getTitle().setFont(new Font("SansSerif", Font.BOLD, 12));

                charts.get(efId).add(chart);
            }
        }
    }

    /*
     * DATES
     */
    charts.put(-1L, new ArrayList<JFreeChart>());
    for (Integer component : dateCorrelations.keySet()) {
        String xaxisLabel = componentShorthand + (component + 1);

        List<Date> dates = svdo.getDates();
        if (dates.isEmpty())
            break;

        long secspan = ubic.basecode.util.DateUtil.numberOfSecondsBetweenDates(dates);

        if (component >= MAX_COMP)
            break;
        Double a = dateCorrelations.get(component);

        if (a != null && !Double.isNaN(a)) {
            Double[] eigenGene = svdo.getvMatrix().getColObj(component);

            /*
             * Plot eigengene vs values, add correlation to the plot
             */
            TimeSeries series = new TimeSeries("Dates vs. eigen" + (component + 1));
            int i = 0;
            for (Date d : dates) {
                // if span is less than an hour, retain the minute.
                if (secspan < 60 * 60) {
                    series.addOrUpdate(new Minute(d), eigenGene[i++]);
                } else {
                    series.addOrUpdate(new Hour(d), eigenGene[i++]);
                }

            }
            TimeSeriesCollection dataset = new TimeSeriesCollection();
            dataset.addSeries(series);

            JFreeChart chart = ChartFactory.createTimeSeriesChart(
                    "Dates: " + xaxisLabel + " " + String.format("r=%.2f", a), null, xaxisLabel, dataset, false,
                    false, false);

            XYPlot xyPlot = chart.getXYPlot();

            chart.getTitle().setFont(new Font("SansSerif", Font.BOLD, 12));

            // standard renderer makes lines.
            XYDotRenderer renderer = new XYDotRenderer();
            renderer.setBaseFillPaint(Color.white);
            renderer.setDotHeight(3);
            renderer.setDotWidth(3);
            renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3)); // has no effect, need dotheight.
            float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP);
            renderer.setSeriesPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f));
            ValueAxis domainAxis = xyPlot.getDomainAxis();
            domainAxis.setVerticalTickLabels(true);
            xyPlot.setRenderer(renderer);
            xyPlot.setRangeGridlinesVisible(false);
            xyPlot.setDomainGridlinesVisible(false);
            charts.get(-1L).add(chart);

        }
    }

    /*
     * Plot in a grid, with each factor as a column. FIXME What if we have too many factors to fit on the screen?
     */
    int columns = (int) Math.ceil(charts.size());
    int perChartSize = ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX;
    BufferedImage image = new BufferedImage(columns * perChartSize, MAX_COMP * perChartSize,
            BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = image.createGraphics();
    int currentX = 0;
    int currentY = 0;
    for (Long id : charts.keySet()) {
        for (JFreeChart chart : charts.get(id)) {
            this.addChartToGraphics(chart, g2, currentX, currentY, perChartSize, perChartSize);
            if (currentY + perChartSize < MAX_COMP * perChartSize) {
                currentY += perChartSize;
            } else {
                currentY = 0;
                currentX += perChartSize;
            }
        }
    }

    os.write(ChartUtilities.encodeAsPNG(image));
    return true;
}

From source file:org.jfree.chart.ChartFactory.java

public static <T extends Number> CategoryDataset createMultiValueCategoryDataset(Map<String, List<T>> dataset) {
    DefaultMultiValueCategoryDataset data = new DefaultMultiValueCategoryDataset();
    List<String> categoryLabels = new ArrayList<String>(dataset.size());
    for (String category : dataset.keySet()) {
        categoryLabels.add(category);//from  ww  w.  jav a 2 s .c  om
    }

    for (String category : categoryLabels) {
        List<T> categoryData = dataset.get(category);
        data.add(categoryData, "", category);
    }

    return data;
}

From source file:org.jfree.chart.ChartFactory.java

public static <T extends Number> CategoryDataset create2DMultiValueCategoryDataset(
        Map<String[], List<T>> dataset) {
    DefaultMultiValueCategoryDataset data = new DefaultMultiValueCategoryDataset();
    List<String[]> categoryLabels = new ArrayList<String[]>(dataset.size());
    for (String[] category : dataset.keySet()) {
        categoryLabels.add(category);/*from  w ww  .j  a va 2 s  .  c om*/
    }

    for (String[] category : categoryLabels) {
        List<T> categoryData = dataset.get(category);
        data.add(categoryData, category[0], category[1]);
    }

    return data;
}