Example usage for org.jfree.chart.plot XYPlot addAnnotation

List of usage examples for org.jfree.chart.plot XYPlot addAnnotation

Introduction

In this page you can find the example usage for org.jfree.chart.plot XYPlot addAnnotation.

Prototype

public void addAnnotation(XYAnnotation annotation) 

Source Link

Document

Adds an annotation to the plot and sends a PlotChangeEvent to all registered listeners.

Usage

From source file:gov.nih.nci.rembrandt.web.plots.RBTPrincipalComponentAnalysisPlot.java

/**
 * This chart uses the XYAnnotation as a glyph to represent
 * a single pca data point. Glyph shape is determined by survival time.
 * Survival of more than 10 months is represented by a circle. 10 months or less
 * is represented by a square. Component1 values are represented by X 
 * Component2 values are represented by Y
 *//* ww w  .ja v a  2s. c o m*/
protected void createGlyphsAndAddToPlot(XYPlot plot) {

    //for RBT, if its non_tumor, show a diamond meaning "N/A for survival"

    XYShapeAnnotation glyph;
    Shape glyphShape;
    Color glyphColor;

    PrincipalComponentAnalysisDataPoint pcaPoint;
    double x, y;
    for (Iterator i = dataPoints.iterator(); i.hasNext();) {
        pcaPoint = (PrincipalComponentAnalysisDataPoint) i.next();

        x = pcaPoint.getComponentValue(component1);
        y = pcaPoint.getComponentValue(component2);
        double survival = pcaPoint.getSurvivalInMonths();
        String diseaseName = pcaPoint.getDiseaseName();

        if (this.colorBy.equals(PCAcolorByType.NONE)) {
            Ellipse2D.Double circle = new Ellipse2D.Double();
            circle.setFrameFromCenter(x, y, x + 2, y + 2);
            glyphShape = circle;
        } else if (diseaseName.equals(RembrandtConstants.NON_TUMOR) || diseaseName.equals("CELL_LINE")) {
            //glyphShape = ShapeUtilities.createDiamond(new Float(x));
            Rectangle2D.Double rect = new Rectangle2D.Double();
            rect.setFrameFromCenter(x, y, x + 2, y + 2);
            glyphShape = rect;
            Shape gShape = ShapeUtilities.rotateShape(glyphShape, new Double(0.785398163), new Float(x),
                    new Float(y));
            glyphShape = gShape;
        } else if ((survival > 0) && (survival < 10.0)) {
            Rectangle2D.Double rect = new Rectangle2D.Double();
            rect.setFrameFromCenter(x, y, x + 2, y + 2);
            glyphShape = rect;
        } else if ((survival > 0) && (survival >= 10.0)) {
            Ellipse2D.Double circle = new Ellipse2D.Double();
            circle.setFrameFromCenter(x, y, x + 2, y + 2);
            glyphShape = circle;
        } else {
            GeneralPath gp = new GeneralPath();
            float xf = (float) x;
            float yf = (float) y;
            //make a triangle
            gp.moveTo(xf, yf);
            gp.lineTo(xf + 3.0f, yf - 3.0f);
            gp.lineTo(xf - 3.0f, yf - 3.0f);
            gp.closePath();
            glyphShape = gp;
        }

        glyphColor = getColorForDataPoint(pcaPoint);
        glyph = new XYShapeAnnotation(glyphShape, new BasicStroke(1.0f), Color.BLACK, glyphColor);
        String tooltip = "";
        if (pcaPoint.getSurvivalInMonths() <= 0.0) {
            tooltip = pcaPoint.getSampleId() + " " + pcaPoint.getDiseaseName();
        } else {
            tooltip = pcaPoint.getSampleId() + " " + pcaPoint.getDiseaseName() + " survivalMonths="
                    + nf.format(pcaPoint.getSurvivalInMonths());
        }
        glyph.setToolTipText(tooltip);
        plot.addAnnotation(glyph);
    }

}

From source file:gov.nih.nci.ispy.ui.graphing.chart.plot.ISPYPrincipalComponentAnalysisPlot.java

/**
 * This chart uses the XYAnnotation as a glyph to represent
 * a single pca data point. Glyph shape is determined by survival time.
 * Survival of more than 10 months is represented by a circle. 10 months or less
 * is represented by a square. Component1 values are represented by X 
 * Component2 values are represented by Y
 *///from  ww  w .  java2  s . co m
private void createGlyphsAndAddToPlot(XYPlot plot, double glyphScaleFactor) {
    XYShapeAnnotation glyph;
    Shape glyphShape = null;
    Color glyphColor;

    double glyphSize = 8.0; //pixels

    double glyphIncrement = (glyphSize * glyphScaleFactor) / 2.0;
    float gi = (float) glyphIncrement;

    ISPYPCADataPoint pcaPoint;
    double x, y;
    for (Iterator i = dataPoints.iterator(); i.hasNext();) {
        pcaPoint = (ISPYPCADataPoint) i.next();

        x = pcaPoint.getComponentValue(component1);
        y = pcaPoint.getComponentValue(component2);

        Double mriPctChange = pcaPoint.getTumorMRIpctChange();

        if (mriPctChange == null) {
            //data is missing
            Rectangle2D.Double rect = new Rectangle2D.Double();
            //rect.setFrameFromCenter(x,y, x+1.25,y+1.25);
            rect.setFrameFromCenter(x, y, x + glyphIncrement, y + glyphIncrement);
            glyphShape = rect;
        } else if (mriPctChange <= -30.0) {

            //tumor shrank by more than 30% (down arrow)
            GeneralPath gp = new GeneralPath();
            float xf = (float) x;
            float yf = (float) y;

            //make a triangle
            gp.moveTo(xf, yf);
            gp.lineTo(xf - gi, yf + gi);
            gp.lineTo(xf + gi, yf + gi);
            gp.closePath();
            glyphShape = gp;
        } else if (mriPctChange > 0.0) {
            //tumor size increased (up arrow)

            GeneralPath gp = new GeneralPath();
            float xf = (float) x;
            float yf = (float) y;
            //make a triangle
            gp.moveTo(xf, yf);
            gp.lineTo(xf + gi, yf - gi);
            gp.lineTo(xf - gi, yf - gi);
            gp.closePath();
            glyphShape = gp;

            //         Ellipse2D.Double circle = new Ellipse2D.Double();
            //         circle.setFrameFromCenter(x,y, x+2, y+2);

        } else if ((mriPctChange > -30.0) && (mriPctChange <= 0.0)) {
            //no change or reduction in tumor size but less than 30% reduction
            Ellipse2D.Double circle = new Ellipse2D.Double();
            //circle.setFrameFromCenter(x,y,x+1.25,y+1.25);
            circle.setFrameFromCenter(x, y, x + gi, y + gi);
            glyphShape = circle;

        }

        glyphColor = getColorForDataPoint(pcaPoint);
        glyph = new XYShapeAnnotation(glyphShape, new BasicStroke(1.0f), Color.BLACK, glyphColor);

        String tooltip = pcaPoint.toString();

        glyph.setToolTipText(tooltip);
        plot.addAnnotation(glyph);
    }

}

From source file:de.bfs.radon.omsimulation.gui.data.OMCharts.java

/**
 * Creates a chart displaying the radon concentration of a virtual campaign.
 * Uses red for normal rooms and blue for cellar rooms.
 * /*from   w  ww  . j a v  a  2s  . c o  m*/
 * @param campaign
 *          The campaign object containing all rooms and radon data.
 * @param preview
 *          Will hide annotations, labels and headlines if true.
 * @return A chart displaying the radon concentration of a virtual campaign.
 */
public static JFreeChart createCampaignChart(OMCampaign campaign, boolean preview) {
    OMRoom[] rooms = new OMRoom[7];
    OMRoom[] tmpRooms = campaign.getRooms();
    OMRoom tmpCellar = campaign.getCellar();
    String variation = campaign.getVariation();
    char[] variationChar = variation.toCharArray();
    int cellarPosition = 0;
    for (int i = 0; i < variationChar.length; i++) {
        if (variationChar[i] == 'C' || variationChar[i] == 'c') {
            cellarPosition = i / 2;
        }
    }
    int c = 0;
    for (int i = 0; i < rooms.length; i++) {
        if (i == cellarPosition) {
            rooms[i] = tmpCellar;
            c++;
        } else {
            rooms[i] = tmpRooms[i - c];
        }
    }
    int start = campaign.getStart();
    final int finalStart = start;
    String title = "Campaign: " + rooms[0].getId() + rooms[1].getId() + rooms[2].getId() + rooms[3].getId()
            + rooms[4].getId() + rooms[5].getId() + rooms[6].getId() + ", Start: " + finalStart;
    int count = 168;
    double[] values = campaign.getValueChain();
    XYSeriesCollection dataSet = new XYSeriesCollection();
    XYSeries roomSeries1 = new XYSeries(" Radon Rooms");
    XYSeries cellarSeries = new XYSeries("Radon Cellar");
    XYSeries roomSeries2 = new XYSeries("Radon Rooms");
    int cellarSeriesStart = cellarPosition * 24;
    int cellarSeriesEnd = cellarSeriesStart + 24;
    double cellarMaximum = campaign.getCellarMaximum();
    double cellarMaximumKey = 0;
    double roomMaximum = campaign.getRoomMaximum();
    double roomMaximumKey = 0;
    if (cellarSeriesStart > 0) {
        for (int i = 0; i < cellarSeriesStart; i++) {
            roomSeries1.add(finalStart + i, values[i]);
            if (values[i] == roomMaximum) {
                roomMaximumKey = i;
            }
        }
    }
    for (int i = cellarSeriesStart - 1; i < cellarSeriesEnd; i++) {
        if (i >= 0) {
            cellarSeries.add(finalStart + i, values[i]);
            if (values[i] == cellarMaximum) {
                cellarMaximumKey = i;
            }
        }
    }
    if (cellarSeriesEnd < count) {
        for (int i = cellarSeriesEnd - 1; i < count; i++) {
            roomSeries2.add(finalStart + i, values[i]);
            if (values[i] == roomMaximum) {
                roomMaximumKey = i;
            }
        }
    }
    dataSet.addSeries(roomSeries1);
    dataSet.addSeries(cellarSeries);
    dataSet.addSeries(roomSeries2);
    JFreeChart chart = ChartFactory.createXYLineChart(title, "T [h]", "Rn [Bq/m\u00B3]", dataSet,
            PlotOrientation.VERTICAL, false, true, false);
    XYPlot plot = (XYPlot) chart.getPlot();
    ValueMarker sepMarker;
    Color sepColor = Color.BLACK;
    float[] sepDash = { 1, 2 };
    Stroke sepStroke = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, sepDash, 0);
    RectangleInsets sepLabelInsets = new RectangleInsets(20, -20, 0, 0);
    Font sepLabelFont = new Font(Font.SANS_SERIF, Font.BOLD, 16);
    sepMarker = new ValueMarker(finalStart + 0, sepColor, sepStroke);
    sepMarker.setLabel(rooms[0].getId());
    sepMarker.setLabelOffset(sepLabelInsets);
    sepMarker.setLabelFont(sepLabelFont);
    plot.addDomainMarker(sepMarker);
    if (rooms[0].getId() != rooms[1].getId()) {
        sepMarker = new ValueMarker(finalStart + 23, sepColor, sepStroke);
        sepMarker.setLabel(rooms[1].getId());
        sepMarker.setLabelOffset(sepLabelInsets);
        sepMarker.setLabelFont(sepLabelFont);
        plot.addDomainMarker(sepMarker);
    }
    if (rooms[1].getId() != rooms[2].getId()) {
        sepMarker = new ValueMarker(finalStart + 47, sepColor, sepStroke);
        sepMarker.setLabel(rooms[2].getId());
        sepMarker.setLabelOffset(sepLabelInsets);
        sepMarker.setLabelFont(sepLabelFont);
        plot.addDomainMarker(sepMarker);
    }
    if (rooms[2].getId() != rooms[3].getId()) {
        sepMarker = new ValueMarker(finalStart + 71, sepColor, sepStroke);
        sepMarker.setLabel(rooms[3].getId());
        sepMarker.setLabelOffset(sepLabelInsets);
        sepMarker.setLabelFont(sepLabelFont);
        plot.addDomainMarker(sepMarker);
    }
    if (rooms[3].getId() != rooms[4].getId()) {
        sepMarker = new ValueMarker(finalStart + 95, sepColor, sepStroke);
        sepMarker.setLabel(rooms[4].getId());
        sepMarker.setLabelOffset(sepLabelInsets);
        sepMarker.setLabelFont(sepLabelFont);
        plot.addDomainMarker(sepMarker);
    }
    if (rooms[4].getId() != rooms[5].getId()) {
        sepMarker = new ValueMarker(finalStart + 119, sepColor, sepStroke);
        sepMarker.setLabel(rooms[5].getId());
        sepMarker.setLabelOffset(sepLabelInsets);
        sepMarker.setLabelFont(sepLabelFont);
        plot.addDomainMarker(sepMarker);
    }
    if (rooms[5].getId() != rooms[6].getId()) {
        sepMarker = new ValueMarker(finalStart + 143, sepColor, sepStroke);
        sepMarker.setLabel(rooms[6].getId());
        sepMarker.setLabelOffset(sepLabelInsets);
        sepMarker.setLabelFont(sepLabelFont);
        plot.addDomainMarker(sepMarker);
    }
    double positiveCellarDeviation = campaign.getCellarAverage() + campaign.getCellarDeviation();
    double negativeCellarDeviation = campaign.getCellarAverage() - campaign.getCellarDeviation();
    IntervalMarker cellarDeviation = new IntervalMarker(negativeCellarDeviation, positiveCellarDeviation);
    float[] dash = { 5, 3 };
    cellarDeviation.setPaint(new Color(222, 222, 255, 128));
    cellarDeviation.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, dash, 0));
    plot.addRangeMarker(cellarDeviation, Layer.BACKGROUND);
    ValueMarker arithCellarMarker = new ValueMarker(campaign.getCellarAverage(), new Color(0, 0, 255, 128),
            new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, dash, 0));
    plot.addRangeMarker(arithCellarMarker);
    XYTextAnnotation amCellarLabel = new XYTextAnnotation("C_AM=" + (int) campaign.getCellarAverage(),
            finalStart + count, campaign.getCellarAverage() * 1.01);
    plot.addAnnotation(amCellarLabel);
    XYTextAnnotation sdCellarLabel = new XYTextAnnotation("C_SD=" + (int) campaign.getCellarDeviation(),
            finalStart + count, (campaign.getCellarAverage() + campaign.getCellarDeviation()) * 1.01);
    plot.addAnnotation(sdCellarLabel);
    ValueMarker maxiCellarMarker = new ValueMarker(cellarMaximum, new Color(0, 0, 255, 128),
            new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, dash, 0));
    plot.addRangeMarker(maxiCellarMarker);
    XYTextAnnotation maxCellarLabel = new XYTextAnnotation("C_MAX=" + (int) cellarMaximum, finalStart + count,
            cellarMaximum * 1.01);
    plot.addAnnotation(maxCellarLabel);
    XYPointerAnnotation maxCellarPointer = new XYPointerAnnotation("", finalStart + cellarMaximumKey,
            cellarMaximum, Math.PI * 1.1);
    plot.addAnnotation(maxCellarPointer);
    double positiveRoomDeviation = campaign.getRoomAverage() + campaign.getRoomDeviation();
    double negativeRoomDeviation = campaign.getRoomAverage() - campaign.getRoomDeviation();
    IntervalMarker roomDeviation = new IntervalMarker(negativeRoomDeviation, positiveRoomDeviation);
    roomDeviation.setPaint(new Color(255, 222, 222, 128));
    roomDeviation.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, dash, 0));
    plot.addRangeMarker(roomDeviation, Layer.BACKGROUND);
    ValueMarker arithRoomMarker = new ValueMarker(campaign.getRoomAverage(), new Color(255, 0, 0, 128),
            new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, dash, 0));
    plot.addRangeMarker(arithRoomMarker);
    XYTextAnnotation amRoomLabel = new XYTextAnnotation("R_AM=" + (int) campaign.getRoomAverage(),
            finalStart + count, campaign.getRoomAverage() * 1.01);
    plot.addAnnotation(amRoomLabel);
    XYTextAnnotation sdRoomLabel = new XYTextAnnotation("R_SD=" + (int) campaign.getRoomDeviation(),
            finalStart + count, (campaign.getRoomAverage() + campaign.getRoomDeviation()) * 1.01);
    plot.addAnnotation(sdRoomLabel);
    ValueMarker maxiRoomMarker = new ValueMarker(roomMaximum, new Color(255, 0, 0, 128),
            new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 1, dash, 0));
    plot.addRangeMarker(maxiRoomMarker);
    XYTextAnnotation maxRoomLabel = new XYTextAnnotation("R_MAX=" + (int) roomMaximum, finalStart + count,
            roomMaximum * 1.01);
    plot.addAnnotation(maxRoomLabel);
    XYPointerAnnotation maxRoomPointer = new XYPointerAnnotation("", finalStart + roomMaximumKey, roomMaximum,
            Math.PI * 1.1);
    plot.addAnnotation(maxRoomPointer);
    XYItemRenderer renderer = plot.getRenderer();
    renderer.setSeriesPaint(0, new Color(255, 0, 0, 128));
    renderer.setSeriesPaint(1, new Color(0, 0, 255, 128));
    renderer.setSeriesPaint(2, new Color(255, 0, 0, 128));
    if (preview) {
        chart.setTitle("");
        plot.clearAnnotations();
    }
    return chart;
}

From source file:org.fhcrc.cpl.viewer.gui.MRMDialog.java

protected void createChartInPanelPrecursorTasksOnly(XYPlot xyp) {
    boolean shouldDisplay = false;

    if (!precursorChromatogramEmpty(transitionOnPlot)) {
        shouldDisplay = true;/*  ww w  .  j  a  va2s.  c  o m*/

        if (!transitionOnPlot.getElutionCurves().isEmpty()) {
            ElutionCurveStrategy ecs = transitionOnPlot.getElutionCurves().values().iterator().next();
            List<ElutionCurve> ecl = ecs.getParentCurves();
            if (ecl != null) {
                for (ElutionCurve e : ecl) {
                    List<Line2D.Double> ll2dd = e.getSegments();
                    for (Line2D.Double l2dd : ll2dd) {
                        xyp.addAnnotation(Utils.line2Annotation(l2dd, new BasicStroke(2.0f),
                                (ecs.isBestParentCurve(e)) ? Color.GREEN : Color.LIGHT_GRAY));
                    }
                }
            }
        }
    }

    precursorContainerContainerPanel.setVisible(shouldDisplay);
    //           updateDaughterCharts(false);
    if (this.getWidth() >= 100 && this.getHeight() >= 100)
        this.setPreferredSize(new Dimension(this.getWidth(), this.getHeight()));
    pack();
}

From source file:com.mgmtp.perfload.loadprofiles.ui.AppFrame.java

private void updateGraph() {
    XYSeriesCollection dataset = new XYSeriesCollection();
    Collection<Stairs> loadProfileEnities = transform(
            filter(loadProfilesController.getTreeItems(), new IsStairsPredicate()),
            new LoadProfileEntityToStairsFunction());
    GraphPointsCalculator calc = new GraphPointsCalculator();
    Map<String, Set<Point>> pointsMap = calc.calculatePoints(loadProfileEnities);

    for (Entry<String, Set<Point>> entry : pointsMap.entrySet()) {
        final XYSeries series = new XYSeries(entry.getKey());
        for (Point point : entry.getValue()) {
            series.add(point.getX(), point.getY());
        }/*from   w ww.  ja v a  2  s . c  om*/
        dataset.addSeries(series);
    }

    String name = txtName.getText();
    chart = ChartFactory.createXYLineChart(name, "t (min)", "Executions (1/h)", dataset,
            PlotOrientation.VERTICAL, true, true, false);

    XYPlot plot = chart.getXYPlot();

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    plot.setRenderer(renderer);

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
    domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    double maxX = 0;

    for (OneTime oneTime : getOneTimes()) {
        String key = oneTime.operation.getName();
        XYSeries series;
        try {
            // We need the series in order to retrieve paint and stroke
            series = dataset.getSeries(key);
        } catch (UnknownKeyException ex) {
            series = new XYSeries(key);
            dataset.addSeries(series);
        }

        int index = dataset.getSeriesIndex(key);
        BasicStroke stroke = (BasicStroke) renderer.lookupSeriesStroke(index);
        stroke = new BasicStroke(stroke.getLineWidth() + 1f, stroke.getEndCap(), stroke.getLineJoin(),
                stroke.getMiterLimit(), stroke.getDashArray(), stroke.getDashPhase());
        Color paint = (Color) renderer.lookupSeriesPaint(index);
        paint = new Color(paint.getRed(), paint.getGreen(), paint.getBlue(), 160);

        double height = rangeAxis.getUpperBound() * .05; // five percent of range
        double width = domainAxis.getUpperBound() * .01; // one percent of range
        double center = oneTime.t0;
        double left = center - width / 2;
        double right = center + width / 2;

        // We only add annotations for one times, but nothing to the series
        plot.addAnnotation(new XYPolygonAnnotation(new double[] { left, 0d, center, height, right, 0d }, stroke,
                paint, paint));

        maxX = max(maxX, right);
    }

    for (Marker marker : getMarkers()) {
        IntervalMarker im = new IntervalMarker(marker.left, marker.right);
        im.setLabel(marker.name);
        im.setLabelFont(new Font(getFont().getName(), getFont().getStyle(), getFont().getSize() + 1));
        im.setLabelAnchor(RectangleAnchor.TOP);
        im.setLabelOffset(new RectangleInsets(8d, 0d, 0d, 0d));
        im.setLabelPaint(Color.BLACK);
        im.setAlpha(.3f);
        im.setPaint(Color.WHITE);
        im.setOutlinePaint(Color.BLACK);
        im.setOutlineStroke(new BasicStroke(1.0f));
        plot.addDomainMarker(im, Layer.BACKGROUND);

        maxX = max(maxX, marker.right);
    }

    if (domainAxis.getUpperBound() < maxX) {
        domainAxis.setUpperBound(maxX * 1.05);
    }
    chartPanel.setChart(chart);
}

From source file:org.trade.ui.chart.CandlestickChart.java

/**
 * A demonstration application showing a candlestick chart.
 * /*ww w .j  av  a2s  . com*/
 * @param title
 *            the frame title.
 * @param strategyData
 *            StrategyData
 */
public CandlestickChart(final String title, StrategyData strategyData, Tradingday tradingday) {

    this.strategyData = strategyData;
    this.setLayout(new BorderLayout());
    // Used to mark the current price
    stroke = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 10, 3 }, 0);
    valueMarker = new ValueMarker(0.00, Color.black, stroke);

    this.chart = createChart(this.strategyData, title, tradingday);

    BlockContainer container = new BlockContainer(new BorderArrangement());
    container.add(titleLegend1, RectangleEdge.LEFT);
    container.add(titleLegend2, RectangleEdge.RIGHT);
    container.add(new EmptyBlock(2000, 0));
    CompositeTitle legends = new CompositeTitle(container);
    legends.setPosition(RectangleEdge.BOTTOM);
    this.chart.addSubtitle(legends);

    final ChartPanel chartPanel = new ChartPanel(this.chart);
    chartPanel.setFillZoomRectangle(true);
    chartPanel.setMouseZoomable(true, true);
    chartPanel.setRefreshBuffer(true);
    chartPanel.setDoubleBuffered(true);
    chartPanel.setVerticalAxisTrace(true);
    chartPanel.setHorizontalAxisTrace(true);
    chartPanel.addChartMouseListener(new ChartMouseListener() {

        public void chartMouseMoved(ChartMouseEvent e) {
        }

        public void chartMouseClicked(final ChartMouseEvent e) {
            CombinedDomainXYPlot combinedXYplot = (CombinedDomainXYPlot) e.getChart().getPlot();
            @SuppressWarnings("unchecked")
            List<XYPlot> subplots = combinedXYplot.getSubplots();
            if (e.getTrigger().getClickCount() == 2) {
                double xItem = 0;
                double yItem = 0;
                if (e.getEntity() instanceof XYItemEntity) {
                    XYItemEntity xYItemEntity = ((XYItemEntity) e.getEntity());
                    xItem = xYItemEntity.getDataset().getXValue(xYItemEntity.getSeriesIndex(),
                            xYItemEntity.getItem());
                    yItem = xYItemEntity.getDataset().getYValue(xYItemEntity.getSeriesIndex(),
                            xYItemEntity.getItem());
                } else {
                    PlotEntity plotEntity = ((PlotEntity) e.getEntity());
                    XYPlot plot = (XYPlot) plotEntity.getPlot();
                    xItem = plot.getDomainCrosshairValue();
                    yItem = plot.getRangeCrosshairValue();
                }

                for (XYPlot xyplot : subplots) {

                    double x = xyplot.getDomainCrosshairValue();
                    double y = xyplot.getRangeCrosshairValue();

                    /*
                     * If the cross hair is from a right-hand y axis we need
                     * to convert this to a left-hand y axis.
                     */
                    String rightAxisName = ", Price: ";
                    double rangeLowerLeft = 0;
                    double rangeUpperLeft = 0;
                    double rangeLowerRight = 0;
                    double rangeUpperRight = 0;
                    double yRightLocation = 0;
                    for (int index = 0; index < xyplot.getRangeAxisCount(); index++) {
                        AxisLocation axisLocation = xyplot.getRangeAxisLocation(index);
                        Range range = xyplot.getRangeAxis(index).getRange();

                        if (axisLocation.equals(AxisLocation.BOTTOM_OR_LEFT)
                                || axisLocation.equals(AxisLocation.TOP_OR_LEFT)) {
                            rangeLowerLeft = range.getLowerBound();
                            rangeUpperLeft = range.getUpperBound();
                            rightAxisName = ", " + xyplot.getRangeAxis(index).getLabel() + ": ";
                        }
                        if (y >= range.getLowerBound() && y <= range.getUpperBound()
                                && (axisLocation.equals(AxisLocation.BOTTOM_OR_RIGHT)
                                        || axisLocation.equals(AxisLocation.TOP_OR_RIGHT))) {
                            rangeUpperRight = range.getUpperBound();
                            rangeLowerRight = range.getLowerBound();
                        }
                    }
                    if ((rangeUpperRight - rangeLowerRight) > 0) {
                        yRightLocation = rangeLowerLeft + ((rangeUpperLeft - rangeLowerLeft)
                                * ((y - rangeLowerRight) / (rangeUpperRight - rangeLowerRight)));
                    } else {
                        yRightLocation = y;
                    }

                    String text = " Time: " + dateFormatShort.format(new Date((long) (x))) + rightAxisName
                            + new Money(y);
                    if (x == xItem && y == yItem) {
                        titleLegend1.setText(text);
                        if (null == clickCrossHairs) {
                            clickCrossHairs = new XYTextAnnotation(text, x, yRightLocation);
                            clickCrossHairs.setTextAnchor(TextAnchor.BOTTOM_LEFT);
                            xyplot.addAnnotation(clickCrossHairs);
                        } else {
                            clickCrossHairs.setText(text);
                            clickCrossHairs.setX(x);
                            clickCrossHairs.setY(yRightLocation);
                        }
                    }
                }
            } else if (e.getTrigger().getClickCount() == 1 && null != clickCrossHairs) {
                for (XYPlot xyplot : subplots) {
                    if (xyplot.removeAnnotation(clickCrossHairs)) {
                        clickCrossHairs = null;
                        titleLegend1.setText(" Time: 0, Price :0.0");
                        break;
                    }
                }
            }
        }
    });
    this.add(chartPanel, null);
    this.strategyData.getCandleDataset().getSeries(0).addChangeListener(this);
}

From source file:cn.InstFS.wkr.NetworkMining.UIs.TimeSeriesChart1.java

public static XYDataset createLineDataset(DataItems dataitems1, DataItems dataitems2,
        Map<String, ArrayList<LinePos>> mapAB, XYPlot xyplot) {
    // ????//from w  ww . j  a  v  a2s .c om
    int modelcount = mapAB.keySet().size();
    long off1 = dataitems1.getElementAt(0).getTime().getTime();
    long off2 = dataitems2.getElementAt(0).getTime().getTime();
    long unit = 0;
    if (dataitems1.getLength() > 0) {
        unit = dataitems1.getElementAt(1).getTime().getTime() - off1;
    } else {
        unit = 3600000;
    }

    XYSeriesCollection xyseriescollection = new XYSeriesCollection();
    // ??

    int colorindex = 0;
    int renderercount = 2;
    for (Object se : mapAB.keySet()) {
        ArrayList<LinePos> s = mapAB.get(se);
        int oneModelCount = s.size();

        ArrayList<DataItems> dslist = new ArrayList<DataItems>();
        Iterator it = s.iterator();

        System.out.println("**************");
        System.out.println("?=" + se + ":=" + oneModelCount);

        XYLineAndShapeRenderer xylineandshaperenderer = new XYLineAndShapeRenderer();
        // ???
        xylineandshaperenderer.setBaseShapesVisible(false);
        // ??
        xylineandshaperenderer.setSeriesLinesVisible(0, true);
        // xylineandshaperenderer.setSeriesShape(0, double1); //?
        // 
        xylineandshaperenderer.setSeriesPaint(0, getcolor(colorindex % 9));
        xylineandshaperenderer.setSeriesFillPaint(0, getcolor(colorindex % 9));
        xylineandshaperenderer.setSeriesOutlinePaint(0, getcolor(colorindex % 9));
        colorindex++;
        xylineandshaperenderer.setUseFillPaint(true);
        xylineandshaperenderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());

        xylineandshaperenderer.setBaseShapesVisible(false);
        xylineandshaperenderer.setSeriesStroke(0,
                new BasicStroke(1.0F, 1, 1, 1.0F, new float[] { 15F, 12F }, 0.0F)); // 
        xylineandshaperenderer.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
        xylineandshaperenderer.setBaseItemLabelsVisible(false);

        while (it.hasNext()) {
            LinePos temp = (LinePos) it.next();

            DataItem d1 = new DataItem();
            d1 = dataitems1.getElementAt(temp.A_start);
            DataItem d2 = new DataItem();
            d2 = dataitems2.getElementAt(temp.B_start);
            DataItems ds1 = new DataItems();
            ds1.add1Data(d1);
            ds1.add1Data(d2);
            // dslist.add(ds1);
            XYDataset xydataset1 = createmodeDataset(ds1, off1, se.toString() + ":" + 1, unit);

            DataItem d3 = new DataItem();
            d3 = dataitems1.getElementAt(temp.A_end);
            DataItem d4 = new DataItem();
            d4 = dataitems2.getElementAt(temp.B_end);
            DataItems ds2 = new DataItems();
            ds2.add1Data(d3);
            ds2.add1Data(d4);
            // dslist.add(ds2);
            XYDataset xydataset2 = createmodeDataset(ds2, off1, se.toString() + ":" + 2, unit);

            int datasetCount = xyplot.getDatasetCount();
            XYTextAnnotation localXYTextAnnotation = null;
            int modelx = (temp.A_start + temp.B_end) / 2;
            double modely = (Double.parseDouble(dataitems2.getElementAt(temp.A_start).getData())
                    + Double.parseDouble(dataitems1.getElementAt(temp.B_end).getData())) / 2;
            /*System.out.println("se=" + se + "::" + "x=" + modelx + "y="
                  + modely);*/
            localXYTextAnnotation = new XYTextAnnotation("" + se + ":" + oneModelCount, modelx, modely);
            xyplot.addAnnotation(localXYTextAnnotation);
            /*System.out.println("datasetCount=" + datasetCount);*/

            xyplot.setDataset(datasetCount, xydataset1);
            xyplot.setRenderer(datasetCount, xylineandshaperenderer);
            xyplot.setDataset(datasetCount + 1, xydataset2);
            xyplot.setRenderer(datasetCount + 1, xylineandshaperenderer);

        }

    }
    return xyseriescollection;
}

From source file:gov.nih.nci.ispy.ui.graphing.chart.plot.ISPYCorrelationScatterPlot.java

private void createGlyphsAndAddToPlot(XYPlot plot, double xScale, double yScale) {
    XYShapeAnnotation glyph;/*from  w  w  w .  ja  va  2  s  . co m*/
    Shape glyphShape = null;
    Color glyphColor;

    //double glyphSize = 8.0;   //pixels

    double glyphIncrementX = (glyphSize * xScale) / 2.0;
    double glyphIncrementY = (glyphSize * yScale) / 2.0;
    float gi_x = (float) glyphIncrementX;
    float gi_y = (float) glyphIncrementY;

    PatientData pd;

    double x, y;
    Double mriPctChange = null;
    for (ISPYPlotPoint corrPoint : dataPoints) {

        x = corrPoint.getX();
        y = corrPoint.getY();

        mriPctChange = corrPoint.getMRITumorPctChange();

        if (mriPctChange == null) {
            //data is missing
            Rectangle2D.Double rect = new Rectangle2D.Double();
            //rect.setFrameFromCenter(x,y, x+1.25,y+1.25);
            rect.setFrameFromCenter(x, y, x + glyphIncrementX, y + glyphIncrementY);
            glyphShape = rect;
        } else if (mriPctChange <= -30.0) {

            //tumor shrank by more than 30% (down arrow)
            GeneralPath gp = new GeneralPath();
            float xf = (float) x;
            float yf = (float) y;

            //make a triangle
            gp.moveTo(xf, yf);
            gp.lineTo(xf - gi_x, yf + gi_y);
            gp.lineTo(xf + gi_x, yf + gi_y);
            gp.closePath();
            glyphShape = gp;
        } else if (mriPctChange > 0.0) {
            //tumor size increased (up arrow)

            GeneralPath gp = new GeneralPath();
            float xf = (float) x;
            float yf = (float) y;
            //make a triangle
            gp.moveTo(xf, yf);
            gp.lineTo(xf + gi_x, yf - gi_y);
            gp.lineTo(xf - gi_x, yf - gi_y);
            gp.closePath();
            glyphShape = gp;

            //            Ellipse2D.Double circle = new Ellipse2D.Double();
            //            circle.setFrameFromCenter(x,y, x+2, y+2);

        } else if ((mriPctChange > -30.0) && (mriPctChange <= 0.0)) {
            //no change or reduction in tumor size but less than 30% reduction
            Ellipse2D.Double circle = new Ellipse2D.Double();
            //circle.setFrameFromCenter(x,y,x+1.25,y+1.25);
            circle.setFrameFromCenter(x, y, x + gi_x, y + gi_y);
            glyphShape = circle;

        }

        //glyphColor = Color.BLUE; 
        //later can set color based on 
        glyphColor = getColorForDataPoint(corrPoint);

        glyph = new XYShapeAnnotation(glyphShape, new BasicStroke(1.0f), Color.BLACK, glyphColor);

        String tooltip = corrPoint.getTag();

        glyph.setToolTipText(tooltip);
        plot.addAnnotation(glyph);
    }

}

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

/**
 * Creates a sample chart.// ww  w.j a va  2  s  . com
 *
 * @param data  the sample data.
 *
 * @return A configured chart.
 */
private JFreeChart createChart(final XYDataset data) {

    final JFreeChart chart = ChartFactory.createScatterPlot("Marker Demo 1", "X", "Y", data,
            PlotOrientation.VERTICAL, true, true, false);
    //    chart.getLegend().setAnchor(Legend.EAST);

    // customise...
    final XYPlot plot = chart.getXYPlot();
    plot.getRenderer().setToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance());

    // set axis margins to allow space for marker labels...
    final DateAxis domainAxis = new DateAxis("Time");
    domainAxis.setUpperMargin(0.50);
    plot.setDomainAxis(domainAxis);

    final ValueAxis rangeAxis = plot.getRangeAxis();
    rangeAxis.setUpperMargin(0.30);
    rangeAxis.setLowerMargin(0.50);

    // add a labelled marker for the bid start price...
    final Marker start = new ValueMarker(200.0);
    start.setPaint(Color.green);
    start.setLabel("Bid Start Price");
    start.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT);
    start.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
    plot.addRangeMarker(start);

    // add a labelled marker for the target price...
    final Marker target = new ValueMarker(175.0);
    target.setPaint(Color.red);
    target.setLabel("Target Price");
    target.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
    target.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
    plot.addRangeMarker(target);

    // add a labelled marker for the original closing time...
    final Hour hour = new Hour(2, new Day(22, 5, 2003));
    double millis = hour.getFirstMillisecond();
    final Marker originalEnd = new ValueMarker(millis);
    originalEnd.setPaint(Color.orange);
    originalEnd.setLabel("Original Close (02:00)");
    originalEnd.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    originalEnd.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
    plot.addDomainMarker(originalEnd);

    // add a labelled marker for the current closing time...
    final Minute min = new Minute(15, hour);
    millis = min.getFirstMillisecond();
    final Marker currentEnd = new ValueMarker(millis);
    currentEnd.setPaint(Color.red);
    currentEnd.setLabel("Close Date (02:15)");
    currentEnd.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
    currentEnd.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    plot.addDomainMarker(currentEnd);

    // ****************************************************************************
    // * JFREECHART DEVELOPER GUIDE                                               *
    // * The JFreeChart Developer Guide, written by David Gilbert, is available   *
    // * to purchase from Object Refinery Limited:                                *
    // *                                                                          *
    // * http://www.object-refinery.com/jfreechart/guide.html                     *
    // *                                                                          *
    // * Sales are used to provide funding for the JFreeChart project - please    * 
    // * support us so that we can continue developing free software.             *
    // ****************************************************************************

    // label the best bid with an arrow and label...
    final Hour h = new Hour(2, new Day(22, 5, 2003));
    final Minute m = new Minute(10, h);
    millis = m.getFirstMillisecond();
    final CircleDrawer cd = new CircleDrawer(Color.red, new BasicStroke(1.0f), null);
    final XYAnnotation bestBid = new XYDrawableAnnotation(millis, 163.0, 11, 11, cd);
    plot.addAnnotation(bestBid);
    final XYPointerAnnotation pointer = new XYPointerAnnotation("Best Bid", millis, 163.0, 3.0 * Math.PI / 4.0);
    pointer.setBaseRadius(35.0);
    pointer.setTipRadius(10.0);
    pointer.setFont(new Font("SansSerif", Font.PLAIN, 9));
    pointer.setPaint(Color.blue);
    pointer.setTextAnchor(TextAnchor.HALF_ASCENT_RIGHT);
    plot.addAnnotation(pointer);

    return chart;

}

From source file:asl.util.PlotMaker2.java

public void writePlot(String fileName) {
    //System.out.format("== plotTitle=[%s] fileName=[%s]\n", plotTitle, fileName);

    File outputFile = new File(fileName);

    // Check that we will be able to output the file without problems and if not --> return
    if (!checkFileOut(outputFile)) {
        System.out.format("== plotMaker: request to output plot=[%s] but we are unable to create it "
                + " --> skip plot\n", fileName);
        return;/* w  w  w. j a v a  2s.co  m*/
    }

    NumberAxis horizontalAxis = new NumberAxis("x-axis default"); // x = domain

    if (fileName.contains("nlnm") || fileName.contains("coher") || fileName.contains("stn")) { // NLNM or StationDeviation 
        horizontalAxis = new LogarithmicAxis("Period (sec)");
        horizontalAxis.setRange(new Range(1, 11000));
        horizontalAxis.setTickUnit(new NumberTickUnit(5.0));
    } else { // EventCompareSynthetics/StrongMotion
        horizontalAxis = new NumberAxis("Time (s)");
        double x[] = panels.get(0).getTraces().get(0).getxData();
        horizontalAxis.setRange(new Range(x[0], x[x.length - 1]));
    }

    CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis);
    combinedPlot.setGap(15.);

    // Loop over (3) panels for this plot:

    for (Panel panel : panels) {

        NumberAxis verticalAxis = new NumberAxis("y-axis default"); // y = range

        if (fileName.contains("nlnm") || fileName.contains("stn")) { // NLNM or StationDeviation 
            verticalAxis = new NumberAxis("PSD 10log10(m**2/s**4)/Hz dB");
            verticalAxis.setRange(new Range(-190, -95));
            verticalAxis.setTickUnit(new NumberTickUnit(5.0));
        } else if (fileName.contains("coher")) { // Coherence
            verticalAxis = new NumberAxis("Coherence, Gamma");
            verticalAxis.setRange(new Range(0, 1.2));
            verticalAxis.setTickUnit(new NumberTickUnit(0.1));
        } else { // EventCompareSynthetics/StrongMotion
            verticalAxis = new NumberAxis("Displacement (m)");
        }

        Font fontPlain = new Font("Verdana", Font.PLAIN, 14);
        Font fontBold = new Font("Verdana", Font.BOLD, 18);
        verticalAxis.setLabelFont(fontBold);
        verticalAxis.setTickLabelFont(fontPlain);
        horizontalAxis.setLabelFont(fontBold);
        horizontalAxis.setTickLabelFont(fontPlain);

        XYSeriesCollection seriesCollection = new XYSeriesCollection();
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, horizontalAxis, verticalAxis, renderer);
        xyplot.setDomainGridlinesVisible(true);
        xyplot.setRangeGridlinesVisible(true);
        xyplot.setRangeGridlinePaint(Color.black);
        xyplot.setDomainGridlinePaint(Color.black);

        // Plot each trace on this panel:
        int iTrace = 0;
        for (Trace trace : panel.getTraces()) {

            XYSeries series = new XYSeries(trace.getName());

            double xdata[] = trace.getxData();
            double ydata[] = trace.getyData();
            for (int k = 0; k < xdata.length; k++) {
                series.add(xdata[k], ydata[k]);
            }

            renderer.setSeriesPaint(iTrace, trace.getColor());
            renderer.setSeriesStroke(iTrace, trace.getStroke());
            renderer.setSeriesLinesVisible(iTrace, true);
            renderer.setSeriesShapesVisible(iTrace, false);

            seriesCollection.addSeries(series);

            iTrace++;
        }

        // Add Annotations for each trace - This is done in a separate loop so that
        //                      the upper/lower limits for this panel will be known
        double xmin = horizontalAxis.getRange().getLowerBound();
        double xmax = horizontalAxis.getRange().getUpperBound();
        double ymin = verticalAxis.getRange().getLowerBound();
        double ymax = verticalAxis.getRange().getUpperBound();
        double delX = Math.abs(xmax - xmin);
        double delY = Math.abs(ymax - ymin);

        // Annotation (x,y) in normalized units - where upper-right corner = (1,1)
        double xAnn = 0.97; // Right center coords of the trace name (e.g., "00-LHZ")
        double yAnn = 0.95;

        double yOff = 0.05; // Vertical distance between different trace legends

        iTrace = 0;
        for (Trace trace : panel.getTraces()) {
            if (!trace.getName().contains("NLNM") && !trace.getName().contains("NHNM")) {
                // x1 > x2 > x3, e.g.:
                //  o-------o   00-LHZ
                //  x3     x2       x1

                double scale = .01; // Controls distance between trace label and line segment
                double xL = .04; // Length of trace line segment in legend

                double xAnn2 = xAnn - scale * trace.getName().length();
                double xAnn3 = xAnn - scale * trace.getName().length() - xL;

                double x1 = xAnn * delX + xmin; // Right hand x-coord of text in range units
                double x2 = xAnn2 * delX + xmin; // x-coord of line segment end in range units
                double x3 = xAnn3 * delX + xmin; // x-coord of line segment end in range units

                double y = (yAnn - (iTrace * yOff)) * delY + ymin;

                if (horizontalAxis instanceof LogarithmicAxis) {
                    double logMin = Math.log10(xmin);
                    double logMax = Math.log10(xmax);
                    delX = logMax - logMin;
                    x1 = Math.pow(10, xAnn * delX + logMin);
                    x2 = Math.pow(10, xAnn2 * delX + logMin);
                    x3 = Math.pow(10, xAnn3 * delX + logMin);
                }
                xyplot.addAnnotation(new XYLineAnnotation(x3, y, x2, y, trace.getStroke(), trace.getColor()));
                XYTextAnnotation xyText = new XYTextAnnotation(trace.getName(), x1, y);
                xyText.setFont(new Font("Verdana", Font.BOLD, 18));
                xyText.setTextAnchor(TextAnchor.CENTER_RIGHT);
                xyplot.addAnnotation(xyText);
            }
            iTrace++;
        }

        combinedPlot.add(xyplot, 1);

    } // panel

    final JFreeChart chart = new JFreeChart(combinedPlot);
    chart.setTitle(new TextTitle(plotTitle, new Font("Verdana", Font.BOLD, 18)));
    chart.removeLegend();

    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, 1400, 1400);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");

    }

}