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.gephi.ui.utils.ChartsUtils.java

/**
 * Build new histogram from the given numbers array using a default title and xLabel.
 * String dataName will be used for yLabel.
 * @param numbers Numbers for the histogram
 * @param dataName Name of the numbers data
 * @param divisions Divisions for the histogram
 * @return Prepared histogram//from   ww  w .  j  a  v a2  s .c  o  m
 */
public static JFreeChart buildHistogram(final Number[] numbers, final String dataName, final int divisions) {
    if (numbers == null || numbers.length == 0) {
        return null;
    }

    HistogramDataset dataset = new HistogramDataset();
    dataset.setType(HistogramType.FREQUENCY);
    double[] doubleNumbers = new double[numbers.length];
    for (int i = 0; i < doubleNumbers.length; i++) {
        doubleNumbers[i] = numbers[i].doubleValue();
    }

    dataset.addSeries(dataName, doubleNumbers, divisions > 0 ? divisions : 10);//Use 10 divisions if divisions number is invalid.

    JFreeChart histogram = ChartFactory.createHistogram(getMessage("ChartsUtils.report.histogram.title"),
            dataName, getMessage("ChartsUtils.report.histogram.yLabel"), dataset, PlotOrientation.VERTICAL,
            true, true, false);

    return histogram;
}

From source file:task5.deneme.java

private ChartPanel createChartPanel() {
    dataset = new HistogramDataset();
    final int w = img.getWidth();
    final int h = img.getHeight();

    JFreeChart chart = ChartFactory.createHistogram("Histogram", "Value", "Count", dataset,
            PlotOrientation.VERTICAL, true, true, false);
    XYPlot plot = (XYPlot) chart.getPlot();
    renderer = (XYBarRenderer) plot.getRenderer();
    renderer.setBarPainter(new StandardXYBarPainter());
    double redd[] = new double[red.size()];
    for (int i = 0; i < red.size(); i++) {
        redd[i] = (int) r[i];
    }/*ww  w.  ja v  a2 s . co  m*/
    dataset.addSeries("Red", redd, 256);

    double greenn[] = new double[green.size()];
    for (int i = 0; i < green.size(); i++) {
        greenn[i] = (int) g[i];
    }
    dataset.addSeries("Green", greenn, 256);

    double bluee[] = new double[blue.size()];
    for (int i = 0; i < blue.size(); i++) {
        bluee[i] = (int) b[i];
    }
    dataset.addSeries("Blue", bluee, 256);

    Paint[] paintArray = { new Color(0x80ff0000, true), new Color(0x8000ff00, true),
            new Color(0x800000ff, true) };

    plot.setDrawingSupplier(
            new DefaultDrawingSupplier(paintArray, DefaultDrawingSupplier.DEFAULT_FILL_PAINT_SEQUENCE,
                    DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,
                    DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
                    DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
                    DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE));
    ChartPanel panel = new ChartPanel(chart);
    panel.setMouseWheelEnabled(true);
    return panel;
}

From source file:herbie.running.analysis.ModeSharesEventHandler.java

public HistogramDataset getHistogramDataset(final int nBins) {
    HistogramDataset output = new HistogramDataset();
    output.setType(HistogramType.RELATIVE_FREQUENCY);

    for (String mode : this.rawData.keySet()) {
        output.addSeries(mode, this.rawData.get(mode).getElements(), nBins);
    }/*www. j  a va  2 s  . com*/

    return output;
}

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.
 * /* w  w  w .  j  a v a 2 s.  com*/
 * @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.compomics.cell_coord.gui.controller.computation.ComputationDataController.java

/**
 *
 * @param track/*w  w  w  . j ava2s  . com*/
 */
private void plotDeltaY(Track track) {
    Double[] deltaYValues = ComputationUtils.transpose2DArray(track.getSteps())[1];
    double[] values = ArrayUtils.toPrimitive(ComputationUtils.excludeNullValues(deltaYValues));
    HistogramDataset histogramDataset = new HistogramDataset();
    histogramDataset.addSeries("", values, 2);
    String title = "delta_y_values for track: " + track.getTrackid();
    JFreeChart jFreeChart = ChartFactory.createHistogram(title, "delta_y", "count", histogramDataset,
            PlotOrientation.VERTICAL, true, true, true);
    ChartPanel chartPanel = new ChartPanel(jFreeChart);
    computationDataPanel.getDeltayPlotPanel().removeAll();
    computationDataPanel.getDeltayPlotPanel().add(chartPanel, gridBagConstraints);
    computationDataPanel.getDeltayPlotPanel().revalidate();
    computationDataPanel.getDeltayPlotPanel().repaint();
}

From source file:se.sics.kompics.p2p.monitor.cyclon.server.CyclonMonitorServer.java

private void printAlivePeers(StringBuilder sb, boolean showPeers) {

    long t0 = System.currentTimeMillis();
    GraphUtil g = new GraphUtil(alivePeers);
    long t1 = System.currentTimeMillis();

    double id, od, cc, pl, istd;
    int diameter;

    id = g.getMeanInDegree();//from   w  w w.j a  va 2s.  c  om
    istd = g.getInDegreeStdDev();
    od = g.getMeanOutDegree();
    cc = g.getMeanClusteringCoefficient();
    pl = g.getMeanPathLength();
    diameter = g.getDiameter();
    int netSize = g.getNetworkSize();

    sb.append("<h2 align=\"center\" class=\"style2\">");
    sb.append("View of Cyclon Random Overlay:</h2>");
    sb.append("<table width=\"400\" border=\"1\" align=\"center\"><tr>");
    sb.append("<th class=\"style2\" width=\"250\" scope=\"col\">Metric");
    sb.append("</th><th class=\"style2\"");
    sb.append(" width=\"150\" scope=\"col\">Value</th></tr><tr>");

    sb.append("<td>Network size</td><td><div align=\"center\">");
    sb.append(netSize).append("</div></td></tr>");
    sb.append("<td>Disconnected node pairs</td><td><div align=\"center\">");
    sb.append(g.getInfinitePathCount()).append("/");
    sb.append(netSize * (netSize - 1)).append("</div></td></tr>");
    sb.append("<td>Diameter</td><td><div align=\"center\">");
    sb.append(diameter).append("</div></td></tr>");
    sb.append("<td>Average path length</td><td><div align=\"center\">");
    sb.append(String.format("%.4f", pl)).append("</div></td></tr>");
    sb.append("<td>Clustering-coefficient</td><td><div align=\"center\">");
    sb.append(String.format("%.4f", cc)).append("</div></td></tr>");
    sb.append("<td>Average in-degree</td><td><div align=\"center\">");
    sb.append(String.format("%.4f", id)).append("</div></td></tr>");
    sb.append("<td>In-degree standard deviation</td><td><div align=\"center\">");
    sb.append(String.format("%.4f", istd)).append("</div></td></tr>");
    sb.append("<td>Average out-degree</td><td><div align=\"center\">");
    sb.append(String.format("%.4f", od)).append("</div></td></tr>");
    sb.append("</table>");

    // print in-degree distribution
    HistogramDataset dataset = new HistogramDataset();
    double[] values = g.getInDegrees();
    int min = (int) g.getMinInDegree(), max = (int) g.getMaxInDegree();
    int bins = max - min;
    bins = bins < 1 ? 1 : bins;
    dataset.addSeries("In-degree distribution", values, bins, min, max);
    JFreeChart chart = ChartFactory.createHistogram(null, null, null, dataset, PlotOrientation.VERTICAL, true,
            false, false);
    // chart.getXYPlot().setForegroundAlpha(0.95f);
    BufferedImage image = chart.createBufferedImage(800, 300);

    String imageString = "";
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ImageIO.write(image, "png", out);
        out.close();
        Base64 bencoder = new Base64();
        imageString = new String(bencoder.encode(out.toByteArray()));
        imageString = "data:image/png;base64," + imageString;
    } catch (IOException e) {
        sb.append(e);
    }

    sb.append("<br><div align=\"center\"><img src=\"").append(imageString);
    sb.append("\" alt=\"In-degree distribution " + "\" /></div><br>");

    sb.append("<div align=\"center\">It took ").append(t1 - t0);
    sb.append("ms to compute these statistics.<br>");

    // refresh form
    sb.append("<form method=\"get\" name=\"rfrshFrm\" id=\"rfrshFrm\">");
    sb.append("<label>Show peers ");
    sb.append("<input name=\"peers\" type=\"checkbox\" id=\"peers\" />");
    // sb.append("checked=\"").append("false").append("\" />");
    sb.append("<input type=\"submit\" value=\"Refresh\" />");
    sb.append("</form></div>");

    if (!showPeers) {
        return;
    }

    sb.append("<h2 align=\"center\" class=\"style2\">");
    sb.append("Individual peers:</h2>");
    sb.append("<table width=\"1300\" border=\"1\" align=\"center\"><tr>");
    sb.append("<th class=\"style2\" width=\"50\" scope=\"col\">Count</th>");
    sb.append("<th class=\"style2\" width=\"50\" scope=\"col\">Peer</th>");
    sb.append("<th class=\"style2\" width=\"800\" scope=\"col\">Neighbors</th>");
    sb.append("<th class=\"style2\" width=\"50\" scope=\"col\">In Degree</th>");
    sb.append("<th class=\"style2\" width=\"50\" scope=\"col\">Out Degree</th>");
    sb.append("<th class=\"style2\" width=\"100\" scope=\"col\">Cluestering Coefficient</th>");
    sb.append("<th class=\"style2\" width=\"50\" scope=\"col\">Age</th>");
    sb.append("<th class=\"style2\" width=\"100\" scope=\"col\">Freshness</th></tr>");

    int count = 1;

    for (OverlayAddress address : alivePeers.keySet()) {
        CyclonNeighbors neighbors = alivePeers.get(address);

        List<CyclonNodeDescriptor> descriptors = neighbors.getDescriptors();
        Collections.sort(descriptors);

        sb.append("<tr>");
        sb.append("<td><div align=\"center\">").append(count++);
        // sb.append("(").append(g.map.get(address)).append(")");
        sb.append("</div></td>");

        // print peer address
        sb.append("</div></td><td bgcolor=\"#99CCFF\"><div align=\"center\">");
        appendPeerLink(sb, address);
        sb.append("</div></td>");

        // print neighbors
        if (descriptors != null) {
            sb.append("<td><div align=\"left\">");
            sb.append("[");
            Iterator<CyclonNodeDescriptor> iter = descriptors.iterator();
            while (iter.hasNext()) {
                appendPeerLink(sb, iter.next().getCyclonAddress());
                if (iter.hasNext()) {
                    sb.append(", ");
                }
            }
            sb.append("]");
        } else {
            sb.append("<td bgcolor=\"#FFCCFF\"><div align=\"left\">");
            sb.append("[empty]");
        }
        sb.append("</div></td>");

        int v = g.getNodeIndexByAddress(address);

        // print in-degree
        sb.append("<td><div align=\"center\">").append(g.getInDegree(v));
        sb.append("</div></td>");
        // print out-degree
        sb.append("<td><div align=\"center\">").append(g.getOutDegree(v));
        sb.append("</div></td>");
        // print clustering coefficient

        // directedGraph

        sb.append("<td><div align=\"center\">").append(String.format("%.4f", g.getClustering(v)));
        sb.append("</div></td>");

        long now = System.currentTimeMillis();
        OverlayViewEntry viewEntry = view.get(address);

        // print age
        sb.append("<td><div align=\"right\">");
        sb.append(durationToString(now - viewEntry.getAddedAt()));
        sb.append("</div></td>");

        // print freshness
        sb.append("<td><div align=\"right\">");
        sb.append(durationToString(now - viewEntry.getRefreshedAt()));
        sb.append("</div></td>");

        sb.append("</tr>");
    }
    sb.append("</table>");
}

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

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

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

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

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

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

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

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

    response.setContentType("image/jpeg");
    OutputStream out = response.getOutputStream();
    ImageIO.write(buf, "jpg", out);
    out.close();/* www .j  a  v a2  s .c o m*/

}

From source file:net.bioclipse.chembl.moss.ui.wizard.ChemblMossWizardPage2.java

@Override
public void createControl(Composite parent) {
    final Composite container = new Composite(parent, SWT.NONE);
    final GridLayout layout = new GridLayout(4, false);
    layout.marginRight = 2;//from  w ww. j  av a 2s  . c o  m
    layout.marginLeft = 2;
    layout.marginBottom = -2;
    layout.marginTop = 10;
    layout.marginWidth = 2;
    layout.marginHeight = 2;
    layout.verticalSpacing = 5;
    layout.horizontalSpacing = 5;
    container.setLayout(layout);

    PlatformUI.getWorkbench().getHelpSystem().setHelp(container, "net.bioclipse.moss.business.helpmessage");
    setControl(container);
    setMessage("Select the first protein family to compare with substructure mining.");
    setPageComplete(true);

    label = new Label(container, SWT.NONE);
    gridData = new GridData(GridData.FILL);
    gridData.grabExcessHorizontalSpace = true;
    gridData.horizontalSpan = 2;
    label.setLayoutData(gridData);
    label.setText("Choose Kinase Protein Familes");

    cbox = new Combo(container, SWT.READ_ONLY);
    cbox.setToolTipText("Kinase family");
    gridData = new GridData();
    gridData.grabExcessHorizontalSpace = true;
    gridData.horizontalSpan = 2;
    gridData.widthHint = 100;
    cbox.setLayoutData(gridData);
    String[] items = { "TK", "TKL", "STE", "CK1", "CMGC", "AGC", "CAMK" };
    cbox.setItems(items);
    cbox.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            final String selected = cbox.getItem(cbox.getSelectionIndex());

            try {
                table.clearAll();
                table.removeAll();
                setErrorMessage(null);
                List<String> list = chembl.mossAvailableActivities(selected);
                if (list.size() > 0) {
                    String[] item = new String[list.size()];
                    for (int i = 0; i < list.size(); i++) {
                        item[i] = list.get(i);
                    }
                    if (cboxAct.isEnabled()) {
                        if (cboxAct.getSelection().x == cboxAct.getSelection().y) {
                            cboxAct.setItems(item);
                        } else {
                            //Solves the problem involving changing the protein family...
                            //Brings the current activities to an array
                            String oldItems[] = cboxAct.getItems();
                            // Takes that array and makes it a list
                            for (int i = 0; i < list.size(); i++) {
                                cboxAct.add(item[i]);
                            }

                            //Remove the old items in the combobox
                            int oldlistsize = cboxAct.getItemCount() - list.size();
                            index = cboxAct.getText();//cboxAct.getItem(cboxAct.getSelectionIndex());
                            cboxAct.remove(0, oldlistsize - 1);
                            //Adds new items to the comboboxlist
                            List<String> oldItemsList = new ArrayList<String>();
                            for (int i = 0; i < oldItems.length; i++) {
                                oldItemsList.add(oldItems[i]);
                            }

                            //New query with the given settings
                            //if(oldItemsList.contains((index))==true){
                            if (list.contains((index)) == true) {

                                spinn.setSelection(50);
                                IStringMatrix matrix, matrix2;
                                try {
                                    matrix = chembl.mossGetCompoundsFromProteinFamilyWithActivity(selected,
                                            index, spinn.getSelection());
                                    matrix2 = chembl.mossGetCompoundsFromProteinFamily(selected, index);
                                    cboxAct.setText(index);
                                    info.setText("Distinct compunds: " + matrix2.getRowCount());
                                    addToTable(matrix);
                                } catch (BioclipseException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }

                            } else {
                                setErrorMessage("The activity " + index
                                        + " does not exist for the protein family " + selected + ".");
                                info.setText("Total compund hit:");
                                setPageComplete(false);

                            }
                        }
                    } else {
                        cboxAct.setItems(item);
                        cboxAct.setEnabled(true);
                    }
                }
            } catch (BioclipseException e1) {
                e1.printStackTrace();
            }
        }
    });

    /*Returns the available compunds for the family*/
    label = new Label(container, SWT.NONE);
    gridData = new GridData(GridData.FILL);
    gridData.grabExcessHorizontalSpace = true;
    gridData.horizontalSpan = 2;
    label.setLayoutData(gridData);
    label.setText("Choose one available activity");

    cboxAct = new Combo(container, SWT.READ_ONLY);
    gridData = new GridData(GridData.FILL);
    gridData.grabExcessHorizontalSpace = true;
    gridData.horizontalSpan = 2;
    gridData.widthHint = 100;
    String[] item = { "No available activity" };
    cboxAct.setItems(item);
    cboxAct.setLayoutData(gridData);
    cboxAct.setEnabled(false);
    cboxAct.setToolTipText("These activities are only accurate for chosen protein");
    //Listener for available activities(IC50, Ki etc)
    cboxAct.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            String selected = cboxAct.getItem(cboxAct.getSelectionIndex());
            try {
                setErrorMessage(null);
                table.clearAll();
                table.removeAll();
                spinn.setSelection(50);
                check.setSelection(false);
                spinnLow.setEnabled(false);
                spinnHigh.setEnabled(false);
                spinnLow.setSelection(0);
                spinnHigh.setSelection(1000);

                //SPARQL queries for fetching compounds and activities
                IStringMatrix matrix = chembl.mossGetCompoundsFromProteinFamilyWithActivity(
                        cbox.getItem(cbox.getSelectionIndex()), selected, spinn.getSelection());
                addToTable(matrix);
                //Count the amount of compounds there is for one hit, i.e. same query without limit.
                IStringMatrix matrix2 = chembl.mossGetCompoundsFromProteinFamily(
                        cbox.getItem(cbox.getSelectionIndex()), cboxAct.getItem(cboxAct.getSelectionIndex()));
                info.setText("Distinct compounds: " + matrix2.getRowCount());
                //Query for activities. Adds them to the plot series.
                matrixAct = chembl.mossGetCompoundsFromProteinFamilyWithActivity(
                        cbox.getItem(cbox.getSelectionIndex()), selected);
                //IStringMatrix matrix = chembl.MossProtFamilyCompounds(cbox.getItem(cbox.getSelectionIndex()), selected,50);
                //IStringMatrix matrix = chembl.MossProtFamilyCompounds(cbox.getItem(cbox.getSelectionIndex()), selected, spinn.getSelection());

                //Adds activity to histogram series
                series = new XYSeries("Activity for compounds");
                histogramSeries = new HistogramDataset();
                histogramSeries.setType(HistogramType.FREQUENCY);
                ArrayList<Double> activites = new ArrayList<Double>();
                double value;
                int cnt = 1;
                double[] histact = new double[matrixAct.getRowCount() + 1];
                for (int i = 1; i < matrixAct.getRowCount() + 1; i++) {
                    if (matrixAct.get(i, "actval").equals("")) {
                        value = 0;
                    } else {
                        value = Double.parseDouble(matrixAct.get(i, "actval"));
                    }
                    activites.add(value);
                }
                //Sort list to increasing order of activities and adds them to histogram
                Collections.sort(activites);
                for (int i = 0; i < activites.size(); i++) {
                    double d = activites.get(i);
                    histact[i] = d;
                    int t = activites.size() - 1;
                    if (i == t) {
                        series.add(d, cnt);
                    } else {
                        double dd = activites.get(i + 1);

                        if (d == dd) {
                            cnt++;
                        } else {
                            histact[i] = d;
                            series.add(d, cnt);
                            cnt = 1;
                        }
                    }
                }
                histogramSeries.addSeries("Histogram", histact, matrixAct.getRowCount());
                button.setEnabled(true);
                spinn.setEnabled(true);
                check.setEnabled(true);
                //cboxAct.setEnabled(true);
                //buttonH.setEnabled(true);

            } catch (BioclipseException e1) {
                e1.printStackTrace();
            }
            setPageComplete(true);
        }
    });

    label = new Label(container, SWT.NONE);
    gridData = new GridData();
    gridData.grabExcessHorizontalSpace = true;
    gridData.horizontalSpan = 2;
    label.setLayoutData(gridData);
    label.setText("Limit");

    spinn = new Spinner(container, SWT.BORDER);
    gridData = new GridData();
    spinn.setLayoutData(gridData);
    spinn.setSelection(50);
    spinn.setMaximum(10000000);
    spinn.setIncrement(50);
    spinn.setEnabled(false);
    gridData.widthHint = 100;
    gridData.horizontalSpan = 1;
    spinn.setToolTipText("Limits the search, increases by 50");
    spinn.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            int selected = spinn.getSelection();
            try {
                table.clearAll();
                table.removeAll();
                IStringMatrix matrix = chembl.mossGetCompounds(cbox.getItem(cbox.getSelectionIndex()),
                        cboxAct.getItem(cboxAct.getSelectionIndex()), selected);
                table.setVisible(true);
                addToTable(matrix);
            } catch (BioclipseException e1) {
                e1.printStackTrace();
            }
        }
    });

    //Button that adds all hits to the limit
    button = new Button(container, SWT.PUSH);
    button.setToolTipText("Add all compounds to the table");
    button.setText("Display all");
    button.setEnabled(false);
    button.setLayoutData(gridData);
    gridData = new GridData();
    gridData.horizontalSpan = 1;
    button.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            //try {
            table.removeAll();
            //            ProgressMonitorDialog dialog = new ProgressMonitorDialog(container.getShell());
            //            
            //            try {
            //               dialog.run(true, true, new IRunnableWithProgress(){
            //                  public void run(IProgressMonitor monitor) {
            //                     monitor.beginTask("Searching for compounds", IProgressMonitor.UNKNOWN);
            try {
                IStringMatrix matrix = chembl.mossGetCompoundsFromProteinFamilyWithActivity(
                        cbox.getItem(cbox.getSelectionIndex()), cboxAct.getItem(cboxAct.getSelectionIndex()));

                //                        final IStringMatrix matrix = chembl.MossProtFamilyCompoundsAct("TK", "Ki");
                addToTable(matrix);
                info.setText("Total hit(not always distinct compounds): " + matrix.getRowCount());
                spinn.setSelection(matrix.getRowCount());

            } catch (BioclipseException eb) {
                // TODO Auto-generated catch block
                eb.printStackTrace();
            }

            //                     
            //                     monitor.done();
            //                  }
            //               });
            //            } catch (InvocationTargetException e1) {
            //               // TODO Auto-generated catch block
            //               e1.printStackTrace();
            //            } catch (InterruptedException e1) {
            //               // TODO Auto-generated catch block
            //               e1.printStackTrace();
            //            }

            //            } catch (BioclipseException e1) {
            //               // TODO Auto-generated catch block
            //               e1.printStackTrace();
            //            }
        }
    });

    label = new Label(container, SWT.NONE);
    label.setText("Optional: Modify activity values.");
    Font font1 = new Font(container.getDisplay(), "Helvetica", 13, SWT.NONE);
    label.setFont(font1);
    gridData = new GridData();
    gridData.horizontalSpan = 4;
    gridData.verticalSpan = 5;
    label.setLayoutData(gridData);

    check = new Button(container, SWT.CHECK);
    check.setText("Modify activities");
    check.setToolTipText("Modify data by specifying upper and lower activity limit");
    check.setEnabled(false);
    gridData = new GridData(GridData.BEGINNING);
    gridData.horizontalSpan = 2;
    check.setLayoutData(gridData);
    check.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            boolean selected = check.getSelection();
            if (selected == true) {
                spinnLow.setEnabled(true);
                spinnHigh.setEnabled(true);
                buttonUpdate.setEnabled(true);
                labelHigh.setEnabled(true);
                labelLow.setEnabled(true);
                buttonH.setEnabled(true);
            } else if (selected == false) {
                spinnLow.setEnabled(false);
                spinnHigh.setEnabled(false);
                buttonUpdate.setEnabled(false);
                labelHigh.setEnabled(false);
                labelLow.setEnabled(false);
                buttonH.setEnabled(false);
            }
        }
    });
    label = new Label(container, SWT.NONE);
    label.setText("Look at activity span: ");
    gridData = new GridData();
    gridData.horizontalSpan = 1;
    label.setLayoutData(gridData);
    buttonH = new Button(container, SWT.PUSH);
    buttonH.setText("Graph");
    buttonH.setToolTipText("Shows activity in a graph(for all compounds)");
    buttonH.setEnabled(false);
    gridData = new GridData();
    gridData.horizontalSpan = 1;
    buttonH.setLayoutData(gridData);
    buttonH.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {

            JFreeChart jfreechart = ChartFactory.createXYLineChart("Histogram Demo", "Activity values",
                    "Number of compounds", histogramSeries, PlotOrientation.VERTICAL, true, false, false);

            //            final XYSeriesCollection dataset = new XYSeriesCollection(series);
            //            JFreeChart chart = ChartFactory.createXYBarChart(
            //                  "Activity chart",
            //                  "Activity value",
            //                  false,
            //                  "Number of Compounds", 
            //                  dataset,
            //                  PlotOrientation.VERTICAL,
            //                  true,
            //                  true,
            //                  false
            //            );
            ChartFrame frame = new ChartFrame("Activities", jfreechart);
            frame.pack();
            frame.setVisible(true);
        }
    });
    // Lower activity bound for updating table
    labelLow = new Label(container, SWT.NONE);
    labelLow.setText("Lower activity limit");
    labelLow.setEnabled(false);
    gridData = new GridData();
    gridData.horizontalSpan = 1;
    labelLow.setLayoutData(gridData);
    spinnLow = new Spinner(container, SWT.NONE);
    spinnLow.setSelection(0);
    spinnLow.setMaximum(10000000);
    spinnLow.setIncrement(50);
    spinnLow.setEnabled(false);
    spinnLow.setToolTipText("Specify lower activity limit");
    gridData = new GridData();
    gridData.widthHint = 100;
    gridData.horizontalSpan = 1;
    spinnLow.setLayoutData(gridData);

    buttonUpdate = new Button(container, SWT.PUSH);
    buttonUpdate.setText("Update table");
    buttonUpdate.setToolTipText("Update the table with the specified activity limits");
    buttonUpdate.setEnabled(false);
    gridData = new GridData();
    gridData.horizontalSpan = 2;
    buttonUpdate.setLayoutData(gridData);
    buttonUpdate.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            table.clearAll();
            table.removeAll();
            try {
                IStringMatrix matrix = chembl.mossSetActivityBound(matrixAct, spinnLow.getSelection(),
                        spinnHigh.getSelection());
                addToTable(matrix);
                spinn.setSelection(matrix.getRowCount());
                info.setText("Total compound hit: " + matrix.getRowCount());
            } catch (BioclipseException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });

    //Upper activity bound for updating table
    labelHigh = new Label(container, SWT.NONE);
    labelHigh.setText("Upper activity limit");
    labelHigh.setEnabled(false);
    gridData = new GridData();
    gridData.horizontalSpan = 1;
    labelHigh.setLayoutData(gridData);
    spinnHigh = new Spinner(container, SWT.BORDER);
    spinnHigh.setSelection(1000);
    spinnHigh.setMaximum(1000000000);
    spinnHigh.setIncrement(50);
    spinnHigh.setEnabled(false);
    spinnHigh.setToolTipText("Specify upper activity limit");
    gridData = new GridData();
    gridData.widthHint = 100;
    gridData.horizontalSpan = 3;
    spinnHigh.setLayoutData(gridData);

    //Label for displaying compound hits
    info = new Label(container, SWT.NONE);
    gridData = new GridData();
    info.setLayoutData(gridData);
    gridData.horizontalSpan = 4;
    gridData.verticalSpan = 6;
    gridData.widthHint = 350;
    info.setText("Total compound hit:");

    //Table displaying contents
    table = new Table(container, SWT.BORDER);
    table.setHeaderVisible(true);
    table.setLinesVisible(true);
    gridData = new GridData();
    gridData.horizontalAlignment = GridData.FILL;
    gridData.verticalAlignment = GridData.FILL;
    gridData.grabExcessHorizontalSpace = true;
    gridData.grabExcessVerticalSpace = true;
    gridData.widthHint = 300;
    gridData.heightHint = 300;
    gridData.horizontalSpan = 4;
    table.setLayoutData(gridData);
    column1 = new TableColumn(table, SWT.NONE);
    column1.setText("Index");
    column2 = new TableColumn(table, SWT.NONE);
    column2.setText("Activity value");
    column3 = new TableColumn(table, SWT.NONE);
    column3.setText("Compounds (SMILES)");
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    XYSeriesCollection lineDatset = new XYSeriesCollection();

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

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

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

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