Example usage for java.awt Color getHSBColor

List of usage examples for java.awt Color getHSBColor

Introduction

In this page you can find the example usage for java.awt Color getHSBColor.

Prototype

public static Color getHSBColor(float h, float s, float b) 

Source Link

Document

Creates a Color object based on the specified values for the HSB color model.

Usage

From source file:gate.gui.docview.AnnotationStack.java

/**
 * Draw the annotation stack in a JPanel with a GridBagLayout.
 *///from w  w  w.  j  a va  2 s.c om
public void drawStack() {

    // clear the panel
    removeAll();

    boolean textTooLong = text.length() > maxTextLength;
    int upperBound = text.length() - (maxTextLength / 2);

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.BOTH;

    /**********************
     * First row of text *
     *********************/

    gbc.gridwidth = 1;
    gbc.insets = new java.awt.Insets(10, 10, 10, 10);
    JLabel labelTitle = new JLabel("Context");
    labelTitle.setOpaque(true);
    labelTitle.setBackground(Color.WHITE);
    labelTitle.setBorder(new CompoundBorder(
            new EtchedBorder(EtchedBorder.LOWERED, new Color(250, 250, 250), new Color(250, 250, 250).darker()),
            new EmptyBorder(new Insets(0, 2, 0, 2))));
    labelTitle.setToolTipText("Expression and its context.");
    add(labelTitle, gbc);
    gbc.insets = new java.awt.Insets(10, 0, 10, 0);

    int expressionStart = contextBeforeSize;
    int expressionEnd = text.length() - contextAfterSize;

    // for each character
    for (int charNum = 0; charNum < text.length(); charNum++) {

        gbc.gridx = charNum + 1;
        if (textTooLong) {
            if (charNum == maxTextLength / 2) {
                // add ellipsis dots in case of a too long text displayed
                add(new JLabel("..."), gbc);
                // skip the middle part of the text if too long
                charNum = upperBound + 1;
                continue;
            } else if (charNum > upperBound) {
                gbc.gridx -= upperBound - (maxTextLength / 2) + 1;
            }
        }

        // set the text and color of the feature value
        JLabel label = new JLabel(text.substring(charNum, charNum + 1));
        if (charNum >= expressionStart && charNum < expressionEnd) {
            // this part is matched by the pattern, color it
            label.setBackground(new Color(240, 201, 184));
        } else {
            // this part is the context, no color
            label.setBackground(Color.WHITE);
        }
        label.setOpaque(true);

        // get the word from which belongs the current character charNum
        int start = text.lastIndexOf(" ", charNum);
        int end = text.indexOf(" ", charNum);
        String word = text.substring((start == -1) ? 0 : start, (end == -1) ? text.length() : end);
        // add a mouse listener that modify the query
        label.addMouseListener(textMouseListener.createListener(word));
        add(label, gbc);
    }

    /************************************
     * Subsequent rows with annotations *
     ************************************/

    // for each row to display
    for (StackRow stackRow : stackRows) {
        String type = stackRow.getType();
        String feature = stackRow.getFeature();
        if (feature == null) {
            feature = "";
        }
        String shortcut = stackRow.getShortcut();
        if (shortcut == null) {
            shortcut = "";
        }

        gbc.gridy++;
        gbc.gridx = 0;
        gbc.gridwidth = 1;
        gbc.insets = new Insets(0, 0, 3, 0);

        // add the header of the row
        JLabel annotationTypeAndFeature = new JLabel();
        String typeAndFeature = type + (feature.equals("") ? "" : ".") + feature;
        annotationTypeAndFeature.setText(!shortcut.equals("") ? shortcut
                : stackRow.getSet() != null ? stackRow.getSet() + "#" + typeAndFeature : typeAndFeature);
        annotationTypeAndFeature.setOpaque(true);
        annotationTypeAndFeature.setBackground(Color.WHITE);
        annotationTypeAndFeature
                .setBorder(new CompoundBorder(new EtchedBorder(EtchedBorder.LOWERED, new Color(250, 250, 250),
                        new Color(250, 250, 250).darker()), new EmptyBorder(new Insets(0, 2, 0, 2))));
        if (feature.equals("")) {
            annotationTypeAndFeature.addMouseListener(headerMouseListener.createListener(type));
        } else {
            annotationTypeAndFeature.addMouseListener(headerMouseListener.createListener(type, feature));
        }
        gbc.insets = new java.awt.Insets(0, 10, 3, 10);
        add(annotationTypeAndFeature, gbc);
        gbc.insets = new java.awt.Insets(0, 0, 3, 0);

        // add all annotations for this row
        HashMap<Integer, TreeSet<Integer>> gridSet = new HashMap<Integer, TreeSet<Integer>>();
        int gridyMax = gbc.gridy;
        for (StackAnnotation ann : stackRow.getAnnotations()) {
            gbc.gridx = ann.getStartNode().getOffset().intValue() - expressionStartOffset + contextBeforeSize
                    + 1;
            gbc.gridwidth = ann.getEndNode().getOffset().intValue() - ann.getStartNode().getOffset().intValue();
            if (gbc.gridx == 0) {
                // column 0 is already the row header
                gbc.gridwidth -= 1;
                gbc.gridx = 1;
            } else if (gbc.gridx < 0) {
                // annotation starts before displayed text
                gbc.gridwidth += gbc.gridx - 1;
                gbc.gridx = 1;
            }
            if (gbc.gridx + gbc.gridwidth > text.length()) {
                // annotation ends after displayed text
                gbc.gridwidth = text.length() - gbc.gridx + 1;
            }
            if (textTooLong) {
                if (gbc.gridx > (upperBound + 1)) {
                    // x starts after the hidden middle part
                    gbc.gridx -= upperBound - (maxTextLength / 2) + 1;
                } else if (gbc.gridx > (maxTextLength / 2)) {
                    // x starts in the hidden middle part
                    if (gbc.gridx + gbc.gridwidth <= (upperBound + 3)) {
                        // x ends in the hidden middle part
                        continue; // skip the middle part of the text
                    } else {
                        // x ends after the hidden middle part
                        gbc.gridwidth -= upperBound - gbc.gridx + 2;
                        gbc.gridx = (maxTextLength / 2) + 2;
                    }
                } else {
                    // x starts before the hidden middle part
                    if (gbc.gridx + gbc.gridwidth < (maxTextLength / 2)) {
                        // x ends before the hidden middle part
                        // do nothing
                    } else if (gbc.gridx + gbc.gridwidth < upperBound) {
                        // x ends in the hidden middle part
                        gbc.gridwidth = (maxTextLength / 2) - gbc.gridx + 1;
                    } else {
                        // x ends after the hidden middle part
                        gbc.gridwidth -= upperBound - (maxTextLength / 2) + 1;
                    }
                }
            }
            if (gbc.gridwidth == 0) {
                gbc.gridwidth = 1;
            }

            JLabel label = new JLabel();
            Object object = ann.getFeatures().get(feature);
            String value = (object == null) ? " " : Strings.toString(object);
            if (value.length() > maxFeatureValueLength) {
                // show the full text in the tooltip
                label.setToolTipText((value.length() > 500)
                        ? "<html><textarea rows=\"30\" cols=\"40\" readonly=\"readonly\">"
                                + value.replaceAll("(.{50,60})\\b", "$1\n") + "</textarea></html>"
                        : ((value.length() > 100)
                                ? "<html><table width=\"500\" border=\"0\" cellspacing=\"0\">" + "<tr><td>"
                                        + value.replaceAll("\n", "<br>") + "</td></tr></table></html>"
                                : value));
                if (stackRow.getCrop() == CROP_START) {
                    value = "..." + value.substring(value.length() - maxFeatureValueLength - 1);
                } else if (stackRow.getCrop() == CROP_END) {
                    value = value.substring(0, maxFeatureValueLength - 2) + "...";
                } else {// cut in the middle
                    value = value.substring(0, maxFeatureValueLength / 2) + "..."
                            + value.substring(value.length() - (maxFeatureValueLength / 2));
                }
            }
            label.setText(value);
            label.setBackground(AnnotationSetsView.getColor(stackRow.getSet(), ann.getType()));
            label.setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
            label.setOpaque(true);

            label.addMouseListener(annotationMouseListener.createListener(stackRow.getSet(), type,
                    String.valueOf(ann.getId())));

            // show the feature values in the tooltip
            if (!ann.getFeatures().isEmpty()) {
                String width = (Strings.toString(ann.getFeatures()).length() > 100) ? "500" : "100%";
                String toolTip = "<html><table width=\"" + width
                        + "\" border=\"0\" cellspacing=\"0\" cellpadding=\"4\">";
                Color color = (Color) UIManager.get("ToolTip.background");
                float[] hsb = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(), null);
                color = Color.getHSBColor(hsb[0], hsb[1], Math.max(0f, hsb[2] - hsb[2] * 0.075f)); // darken the color
                String hexColor = Integer.toHexString(color.getRed()) + Integer.toHexString(color.getGreen())
                        + Integer.toHexString(color.getBlue());
                boolean odd = false; // alternate background color every other row

                List<Object> features = new ArrayList<Object>(ann.getFeatures().keySet());
                //sort the features into alphabetical order
                Collections.sort(features, new Comparator<Object>() {
                    @Override
                    public int compare(Object o1, Object o2) {
                        return o1.toString().compareToIgnoreCase(o2.toString());
                    }
                });

                for (Object key : features) {
                    String fv = Strings.toString(ann.getFeatures().get(key));
                    toolTip += "<tr align=\"left\"" + (odd ? " bgcolor=\"#" + hexColor + "\"" : "")
                            + "><td><strong>" + key + "</strong></td><td>"
                            + ((fv.length() > 500)
                                    ? "<textarea rows=\"20\" cols=\"40\" cellspacing=\"0\">" + StringEscapeUtils
                                            .escapeHtml(fv.replaceAll("(.{50,60})\\b", "$1\n")) + "</textarea>"
                                    : StringEscapeUtils.escapeHtml(fv).replaceAll("\n", "<br>"))
                            + "</td></tr>";
                    odd = !odd;
                }
                label.setToolTipText(toolTip + "</table></html>");
            } else {
                label.setToolTipText("No features.");
            }

            if (!feature.equals("")) {
                label.addMouseListener(annotationMouseListener.createListener(stackRow.getSet(), type, feature,
                        Strings.toString(ann.getFeatures().get(feature)), String.valueOf(ann.getId())));
            }
            // find the first empty row span for this annotation
            int oldGridy = gbc.gridy;
            for (int y = oldGridy; y <= (gridyMax + 1); y++) {
                // for each cell of this row where spans the annotation
                boolean xSpanIsEmpty = true;
                for (int x = gbc.gridx; (x < (gbc.gridx + gbc.gridwidth)) && xSpanIsEmpty; x++) {
                    xSpanIsEmpty = !(gridSet.containsKey(x) && gridSet.get(x).contains(y));
                }
                if (xSpanIsEmpty) {
                    gbc.gridy = y;
                    break;
                }
            }
            // save the column x and row y of the current value
            TreeSet<Integer> ts;
            for (int x = gbc.gridx; x < (gbc.gridx + gbc.gridwidth); x++) {
                ts = gridSet.get(x);
                if (ts == null) {
                    ts = new TreeSet<Integer>();
                }
                ts.add(gbc.gridy);
                gridSet.put(x, ts);
            }
            add(label, gbc);
            gridyMax = Math.max(gridyMax, gbc.gridy);
            gbc.gridy = oldGridy;
        }

        // add a button at the end of the row
        gbc.gridwidth = 1;
        if (stackRow.getLastColumnButton() != null) {
            // last cell of the row
            gbc.gridx = Math.min(text.length(), maxTextLength) + 1;
            gbc.insets = new Insets(0, 10, 3, 0);
            gbc.fill = GridBagConstraints.NONE;
            gbc.anchor = GridBagConstraints.WEST;
            add(stackRow.getLastColumnButton(), gbc);
            gbc.insets = new Insets(0, 0, 3, 0);
            gbc.fill = GridBagConstraints.BOTH;
            gbc.anchor = GridBagConstraints.CENTER;
        }

        // set the new gridy to the maximum row we put a value
        gbc.gridy = gridyMax;
    }

    if (lastRowButton != null) {
        // add a configuration button on the last row
        gbc.insets = new java.awt.Insets(0, 10, 0, 10);
        gbc.gridx = 0;
        gbc.gridy++;
        add(lastRowButton, gbc);
    }

    // add an empty cell that takes all remaining space to
    // align the visible cells at the top-left corner
    gbc.gridy++;
    gbc.gridx = Math.min(text.length(), maxTextLength) + 1;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbc.gridheight = GridBagConstraints.REMAINDER;
    gbc.weightx = 1;
    gbc.weighty = 1;
    add(new JLabel(""), gbc);

    validate();
    updateUI();
}

From source file:Interface.Caruser.Pendingrequest.java

public void populatetable() {

    DefaultTableModel model = (DefaultTableModel) incomingjTable.getModel();

    model.setRowCount(0);//from w  w w  .ja va  2s .  co m
    for (WorkRequest request : organization.getWorkQueue().getWorkRequestList()) {
        Object[] row = new Object[7];
        row[0] = request;
        row[1] = request.getSender();
        row[2] = request.getReceiver();
        row[3] = request.getSource();
        row[4] = request.getDestination();
        Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        row[5] = formatter.format(request.getRequestDate());
        row[6] = request.getStatus();
        model.addRow(row);
    }
    incomingjTable.setSelectionBackground(Color.getHSBColor(0.2F, 0.1F, 0.2F));
    incomingjTable.setSelectionForeground(Color.white);
}

From source file:ala.soils2sat.DrawingUtils.java

public static List<Color> generatePalette(int size, Color baseColor) {
    float[] hsb = { 0, 0, 0 };
    Color.RGBtoHSB(baseColor.getRed(), baseColor.getGreen(), baseColor.getBlue(), hsb);
    double baseHue = hsb[0];

    List<Color> colors = new ArrayList<Color>();
    colors.add(baseColor);//from w w w .  ja  v a 2s.  c o  m

    double step = (240.0 / (double) size);

    for (int i = 1; i < size; ++i) {
        float hue = (float) ((baseHue + step * ((double) i)) % 240.0); // this gives a number out of 240. need to scale that to percent
        hue = hue / 240;
        Color nextColor = Color.getHSBColor(hue, hsb[1], hsb[2]);
        colors.add(nextColor);
    }
    return colors;
}

From source file:GeMSE.GS.Analysis.Stats.OneSamplePCAPanel.java

private void Plot() {
    double[][] data = _principalComponents.getData();
    if (data[0].length < 2) {
        JOptionPane.showMessageDialog(this,
                "An error occured when computing principal components.     "
                        + "\nRequire at least two principal components, but calculated "
                        + String.valueOf(data[0].length) + "\n",
                "Not enough data", JOptionPane.ERROR_MESSAGE);
        return;//  w w  w .j av a 2 s .  c  o  m
    }

    float[] yAxisColor = new float[3];
    Color.RGBtoHSB(255, 255, 255, yAxisColor);

    float[] hsbValues = new float[3];
    Color.RGBtoHSB(16, 23, 67, hsbValues);

    float[] pcColor = new float[3];
    Color.RGBtoHSB(255, 255, 0, pcColor);

    XYSeriesCollection dataset = new XYSeriesCollection();

    XYSeries series = new XYSeries("PC");
    for (double[] d : data)
        series.add(d[0], d[1]);
    dataset.addSeries(series);

    JFreeChart chart = ChartFactory.createScatterPlot(null, "Principal component 1", "Principal component 2",
            (XYDataset) dataset);
    chart.setBackgroundPaint(Color.getHSBColor(hsbValues[0], hsbValues[1], hsbValues[2]));
    chart.removeLegend();

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.getHSBColor(hsbValues[0], hsbValues[1], hsbValues[2]));

    Font axisLabelFont = new Font("Dialog", Font.PLAIN, 14);
    Font axisTickLabelFont = new Font("Dialog", Font.PLAIN, 12);

    plot.setDomainGridlinePaint(Color.gray);
    plot.setRangeGridlinePaint(Color.gray);

    plot.getDomainAxis().setTickLabelPaint(Color.white);
    plot.getDomainAxis().setLabelPaint(Color.white);
    plot.getDomainAxis().setLabelFont(axisLabelFont);
    plot.getDomainAxis().setTickLabelFont(axisTickLabelFont);

    plot.getRangeAxis().setTickLabelPaint(Color.getHSBColor(yAxisColor[0], yAxisColor[1], yAxisColor[2]));
    plot.getRangeAxis().setLabelPaint(Color.getHSBColor(yAxisColor[0], yAxisColor[1], yAxisColor[2]));
    plot.getRangeAxis().setLabelFont(axisLabelFont);
    plot.getRangeAxis().setTickLabelFont(axisTickLabelFont);

    Shape shape = ShapeUtilities.createDiagonalCross(4, 0.5f);
    XYItemRenderer renderer = chart.getXYPlot().getRenderer();
    renderer.setSeriesShape(0, shape);
    renderer.setSeriesPaint(0, Color.getHSBColor(pcColor[0], pcColor[1], pcColor[2]));

    ChartPanel panel = new ChartPanel(chart);
    Dimension plotDim = plotPanel.getSize();
    plotDim.height -= (plotDim.height * 10) / 100;
    plotDim.width -= (plotDim.width * 10) / 100;
    panel.setPreferredSize(plotDim);
    plotPanel.setViewportView(panel);

    revalidate();
    repaint();
}

From source file:org.gwaspi.gui.reports.SampleQAHetzygPlotZoom.java

private JFreeChart createChart(XYDataset dataset) {
    JFreeChart chart = ChartFactory.createScatterPlot("Heterozygosity vs. Missing Ratio",
            "Heterozygosity Ratio", "Missing Ratio", dataset, PlotOrientation.VERTICAL, true, false, false);

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setNoDataMessage("NO DATA");
    plot.setDomainZeroBaselineVisible(true);
    plot.setRangeZeroBaselineVisible(true);

    // CHART BACKGROUD COLOR
    chart.setBackgroundPaint(Color.getHSBColor(0.1f, 0.1f, 1.0f)); // Hue, saturation, brightness
    plot.setBackgroundPaint(PLOT_MANHATTAN_BACKGROUND); // Hue, saturation, brightness 9

    // GRIDLINES/*from w w  w  . j a v  a2  s  .c  o m*/
    plot.setDomainGridlineStroke(new BasicStroke(0.0f));
    plot.setDomainMinorGridlineStroke(new BasicStroke(0.0f));
    plot.setDomainGridlinePaint(PLOT_MANHATTAN_BACKGROUND.darker().darker()); // Hue, saturation, brightness 7
    plot.setDomainMinorGridlinePaint(PLOT_MANHATTAN_BACKGROUND); // Hue, saturation, brightness 9
    plot.setRangeGridlineStroke(new BasicStroke(0.0f));
    plot.setRangeMinorGridlineStroke(new BasicStroke(0.0f));
    plot.setRangeGridlinePaint(PLOT_MANHATTAN_BACKGROUND.darker().darker()); // Hue, saturation, brightness 7
    plot.setRangeMinorGridlinePaint(PLOT_MANHATTAN_BACKGROUND.darker()); // Hue, saturation, brightness 8

    plot.setDomainMinorGridlinesVisible(true);
    plot.setRangeMinorGridlinesVisible(true);

    // DOTS RENDERER
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setSeriesPaint(0, PLOT_MANHATTAN_DOTS);
    //      renderer.setSeriesOutlinePaint(0, Color.DARK_GRAY);
    //      renderer.setUseOutlinePaint(true);
    // Set dot shape of the currently appended Series
    renderer.setSeriesShape(0, new Rectangle2D.Double(-1, -1, 2, 2));

    renderer.setSeriesVisibleInLegend(0, false);

    // AXIS
    double maxHetzy = 0.005;
    for (int i = 0; i < dataset.getItemCount(0); i++) {
        if (maxHetzy < dataset.getXValue(0, i)) {
            maxHetzy = dataset.getXValue(0, i);
        }
    }
    NumberAxis hetzyAxis = (NumberAxis) plot.getDomainAxis();
    hetzyAxis.setAutoRangeIncludesZero(true);
    hetzyAxis.setAxisLineVisible(true);
    hetzyAxis.setTickLabelsVisible(true);
    hetzyAxis.setTickMarksVisible(true);
    hetzyAxis.setRange(0, maxHetzy * 1.1);

    double maxMissrat = 0.005;
    for (int i = 0; i < dataset.getItemCount(0); i++) {
        if (maxMissrat < dataset.getYValue(0, i)) {
            maxMissrat = dataset.getYValue(0, i);
        }
    }
    NumberAxis missratAxis = (NumberAxis) plot.getRangeAxis();
    missratAxis.setAutoRangeIncludesZero(true);
    missratAxis.setAxisLineVisible(true);
    missratAxis.setTickLabelsVisible(true);
    missratAxis.setTickMarksVisible(true);
    missratAxis.setRange(0, maxMissrat * 1.1);

    // Add significance Threshold to subplot
    final Marker missingThresholdLine = new ValueMarker(missingThreshold);
    missingThresholdLine.setPaint(Color.blue);

    final Marker hetzyThresholdLine = new ValueMarker(hetzyThreshold);
    hetzyThresholdLine.setPaint(Color.blue);

    // Add legend to hetzyThreshold
    hetzyThresholdLine.setLabel("hetzyg. threshold = " + hetzyThreshold);
    missingThresholdLine.setLabel("missing. threshold = " + missingThreshold);
    hetzyThresholdLine.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    hetzyThresholdLine.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
    missingThresholdLine.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT);
    missingThresholdLine.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    plot.addRangeMarker(missingThresholdLine); // THIS FOR MISSING RATIO
    plot.addDomainMarker(hetzyThresholdLine); // THIS FOR HETZY RATIO

    // Marker label if below hetzyThreshold
    XYItemRenderer lblRenderer = plot.getRenderer();

    // THRESHOLD AND SELECTED LABEL GENERATOR
    MySeriesItemLabelGenerator lblGenerator = new MySeriesItemLabelGenerator(hetzyThreshold, missingThreshold);
    lblRenderer.setSeriesItemLabelGenerator(0, lblGenerator);
    lblRenderer.setSeriesItemLabelFont(0, new Font("SansSerif", Font.PLAIN, 10));
    lblRenderer.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.CENTER,
            TextAnchor.BOTTOM_LEFT, TextAnchor.BOTTOM_LEFT, 2 * Math.PI));

    // TOOLTIP GENERATOR
    MyXYToolTipGenerator tooltipGenerator = new MyXYToolTipGenerator();

    lblRenderer.setBaseToolTipGenerator(tooltipGenerator);

    lblRenderer.setSeriesItemLabelsVisible(0, true);

    return chart;
}

From source file:com.planetmayo.debrief.satc_rcp.views.SpatialView.java

public static Color[] getDifferentColors(int n) {
    Color[] cols = new Color[n];
    for (int i = 0; i < n; i++)
        cols[i] = Color.getHSBColor((float) (n - i) / n, 1, 1);
    // return cols;
    return randomizeArray(cols);
}

From source file:org.gwaspi.gui.reports.ManhattanPlotZoom.java

private JFreeChart createChart(XYDataset dataset, ChromosomeKey chr) {
    JFreeChart chart = ChartFactory.createScatterPlot(null, "", "P value", dataset, PlotOrientation.VERTICAL,
            true, false, false);/*from  w w w  . jav  a  2 s  .com*/

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setNoDataMessage("NO DATA");
    plot.setDomainZeroBaselineVisible(true);
    plot.setRangeZeroBaselineVisible(true);

    // CHART BACKGROUD COLOR
    chart.setBackgroundPaint(Color.getHSBColor(0.1f, 0.1f, 1.0f)); // Hue, saturation, brightness
    plot.setBackgroundPaint(manhattan_back); // Hue, saturation, brightness 9

    // GRIDLINES
    plot.setDomainGridlineStroke(new BasicStroke(0.0f));
    plot.setDomainMinorGridlineStroke(new BasicStroke(0.0f));
    plot.setDomainGridlinePaint(manhattan_back.darker().darker()); // Hue, saturation, brightness 7
    plot.setDomainMinorGridlinePaint(manhattan_back); // Hue, saturation, brightness 9
    plot.setRangeGridlineStroke(new BasicStroke(0.0f));
    plot.setRangeMinorGridlineStroke(new BasicStroke(0.0f));
    plot.setRangeGridlinePaint(manhattan_back.darker().darker()); // Hue, saturation, brightness 7
    plot.setRangeMinorGridlinePaint(manhattan_back.darker()); // Hue, saturation, brightness 8

    plot.setDomainMinorGridlinesVisible(true);
    plot.setRangeMinorGridlinesVisible(true);

    // DOTS RENDERER
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setSeriesPaint(0, manhattan_dot);
    //      renderer.setSeriesOutlinePaint(0, Color.DARK_GRAY);
    //      renderer.setUseOutlinePaint(true);
    // Set dot shape of the currently appended Series
    renderer.setSeriesShape(0, new Rectangle2D.Double(0.0, 0.0, 2, 2));

    renderer.setSeriesVisibleInLegend(0, false);

    NumberAxis positionAxis = (NumberAxis) plot.getDomainAxis();
    //      domainAxis.setAutoRangeIncludesZero(false);
    //      domainAxis.setTickMarkInsideLength(2.0f);
    //      domainAxis.setTickMarkOutsideLength(2.0f);
    //      domainAxis.setMinorTickCount(2);
    //      domainAxis.setMinorTickMarksVisible(true);
    positionAxis.setLabelAngle(1.0);
    positionAxis.setAutoRangeIncludesZero(false);
    positionAxis.setAxisLineVisible(true);
    positionAxis.setTickLabelsVisible(true);
    positionAxis.setTickMarksVisible(true);

    // ADD INVERSE LOG(10) Y AXIS
    LogAxis logPAxis = new LogAxis("P value");
    logPAxis.setBase(10);
    logPAxis.setInverted(true);
    logPAxis.setNumberFormatOverride(GenericReportGenerator.FORMAT_P_VALUE);

    logPAxis.setTickMarkOutsideLength(2.0f);
    logPAxis.setMinorTickCount(2);
    logPAxis.setMinorTickMarksVisible(true);
    logPAxis.setAxisLineVisible(true);
    logPAxis.setUpperMargin(0);

    TickUnitSource units = NumberAxis.createIntegerTickUnits();
    logPAxis.setStandardTickUnits(units);
    plot.setRangeAxis(0, logPAxis);

    // Add significance Threshold to subplot
    //threshold = 0.5/rdMatrixMetadata.getMarkerSetSize();  // (0.05/10? SNPs => 5*10-?)
    final Marker thresholdLine = new ValueMarker(threshold);
    thresholdLine.setPaint(Color.red);
    // Add legend to threshold
    thresholdLine.setLabel("P = " + GenericReportGenerator.FORMAT_P_VALUE.format(threshold));
    thresholdLine.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
    thresholdLine.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
    plot.addRangeMarker(thresholdLine);

    // Marker label if below threshold
    XYItemRenderer lblRenderer = plot.getRenderer();

    // THRESHOLD AND SELECTED LABEL GENERATOR
    MySeriesItemLabelGenerator lblGenerator = new MySeriesItemLabelGenerator(threshold, chr);
    lblRenderer.setSeriesItemLabelGenerator(0, lblGenerator);
    lblRenderer.setSeriesItemLabelFont(0, new Font("SansSerif", Font.PLAIN, 12));
    lblRenderer.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.CENTER,
            TextAnchor.TOP_LEFT, TextAnchor.BOTTOM_LEFT, Math.PI / 4.0));

    // TOOLTIP GENERATOR
    MyXYToolTipGenerator tooltipGenerator = new MyXYToolTipGenerator(chr);

    lblRenderer.setBaseToolTipGenerator(tooltipGenerator);

    lblRenderer.setSeriesItemLabelsVisible(0, true);

    return chart;
}

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;
    }/*  w  ww  .ja v  a 2 s .co 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:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java

/**
 * Visualization of the correlation of principal components with factors or the date samples were run.
 *
 * @param svdo SVD value object/* w w w.  j  a  va 2 s. c om*/
 */
private void writePCAFactors(OutputStream os, ExpressionExperiment ee, SVDValueObject svdo) throws Exception {
    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());

    if (factorCorrelations.isEmpty() && dateCorrelations.isEmpty()) {
        this.writePlaceholderImage(os);
        return;
    }
    ee = expressionExperimentService.thawLite(ee); // need the experimental design
    int maxWidth = 10;

    Map<Long, String> efs = this.getFactorNames(ee, maxWidth);

    DefaultCategoryDataset series = new DefaultCategoryDataset();

    /*
     * With two groups, or a continuous factor, we get rank correlations
     */
    int MAX_COMP = 3;
    double STUB = 0.05; // always plot a little thing so we know its there.
    for (Integer component : factorCorrelations.keySet()) {
        if (component >= MAX_COMP)
            break;
        for (Long efId : factorCorrelations.get(component).keySet()) {
            Double a = factorCorrelations.get(component).get(efId);
            String facname = efs.get(efId) == null ? "?" : efs.get(efId);
            if (a != null && !Double.isNaN(a)) {
                Double corr = Math.max(STUB, Math.abs(a));
                series.addValue(corr, "PC" + (component + 1), facname);
            }
        }
    }

    for (Integer component : dateCorrelations.keySet()) {
        if (component >= MAX_COMP)
            break;
        Double a = dateCorrelations.get(component);
        if (a != null && !Double.isNaN(a)) {
            Double corr = Math.max(STUB, Math.abs(a));
            series.addValue(corr, "PC" + (component + 1), "Date run");
        }
    }
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    JFreeChart chart = ChartFactory.createBarChart("", "Factors", "Component assoc.", series,
            PlotOrientation.VERTICAL, true, false, false);

    chart.getCategoryPlot().getRangeAxis().setRange(0, 1);
    BarRenderer renderer = (BarRenderer) chart.getCategoryPlot().getRenderer();
    renderer.setBasePaint(Color.white);
    renderer.setShadowVisible(false);
    chart.getCategoryPlot().setRangeGridlinesVisible(false);
    chart.getCategoryPlot().setDomainGridlinesVisible(false);
    ChartUtilities.applyCurrentTheme(chart);

    CategoryAxis domainAxis = chart.getCategoryPlot().getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    for (int i = 0; i < MAX_COMP; i++) {
        /*
         * Hue is straightforward; brightness is set medium to make it muted; saturation we vary from high to low.
         */
        float saturationDrop = (float) Math.min(1.0, i * 1.3f / MAX_COMP);
        renderer.setSeriesPaint(i, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f));

    }

    /*
     * Give figure more room .. up to a limit
     */
    int width = ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX;
    if (chart.getCategoryPlot().getCategories().size() > 3) {
        width = width + 40 * (chart.getCategoryPlot().getCategories().size() - 2);
    }
    int MAX_QC_IMAGE_SIZE_PX = 500;
    width = Math.min(width, MAX_QC_IMAGE_SIZE_PX);
    ChartUtilities.writeChartAsPNG(os, chart, width, ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX);
}

From source file:com.actelion.research.table.view.JVisualization.java

/**
 * Generates a neutral grey with given contrast to given color.
 * @param contrast 0.0 (not visible) to 1.0 (full contrast)
 * @return/*  w w  w  . j av  a 2  s.  c o  m*/
 */
protected Color getContrastGrey(float contrast, Color color) {
    float brightness = ColorHelper.perceivedBrightness(color);
    float range = (brightness > 0.5) ? brightness : 1f - brightness;

    // enhance contrast for middle bright backgrounds
    contrast = (float) Math.pow(contrast, range);

    return (brightness > 0.5) ? Color.getHSBColor(0.0f, 0.0f, brightness - range * contrast)
            : Color.getHSBColor(0.0f, 0.0f, brightness + range * contrast);
}