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

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

Introduction

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

Prototype

public void setDomainGridlinesVisible(boolean visible) 

Source Link

Document

Sets the flag that controls whether or not the domain grid-lines are visible.

Usage

From source file:asl.util.PlotMaker.java

public void plotSpecAmp2(double freq[], double[] amp1, double[] phase1, double[] amp2, double[] phase2,
        String plotTitle, String pngName) {

    /**/*from  w  w  w  .  j  av a2s  . co  m*/
            final String plotTitle = String.format("%04d%03d.%s.%s %s", date.get(Calendar.YEAR), date.get(Calendar.DAY_OF_YEAR)
                                        ,station, channel, plotString);
            final String pngName   = String.format("%s/%04d%03d.%s.%s.%s.png", outputDir, date.get(Calendar.YEAR), date.get(Calendar.DAY_OF_YEAR)
                                        ,station, channel, plotString);
    **/
    File outputFile = new File(pngName);

    // Check that we will be able to output the file without problems and if not --> return
    if (!checkFileOut(outputFile)) {
        System.out.format("== plotSpecAmp: request to output plot=[%s] but we are unable to create it "
                + " --> skip plot\n", pngName);
        return;
    }
    // Plot x-axis (frequency) range
    final double XMIN = .00009;
    final double XMAX = freq[freq.length - 1];

    System.out.format("== plotSpecAmp2: nfreq=%d npts=%d pngName=%s\n", freq.length, amp2.length, pngName);

    final XYSeries series1 = new XYSeries("Amp_PZ");
    final XYSeries series1b = new XYSeries("Amp_Cal");

    final XYSeries series2 = new XYSeries("Phase_PZ");
    final XYSeries series2b = new XYSeries("Phase_Cal");

    double maxdB = 0.;
    for (int k = 0; k < freq.length; k++) {
        double dB = amp1[k];
        //double dB = 20. * Math.log10( amp1[k] );
        //series1.add( freq[k], dB );
        //series1.add( freq[k], 20. * Math.log10( amp1[k] ) );
        //series1b.add(freq[k], 20. * Math.log10( amp2[k] ));
        series1.add(freq[k], amp1[k]);
        series1b.add(freq[k], amp2[k]);
        series2.add(freq[k], phase1[k]);
        series2b.add(freq[k], phase2[k]);
        if (dB > maxdB) {
            maxdB = dB;
        }
    }

    //final XYItemRenderer renderer = new StandardXYItemRenderer();
    final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    Rectangle rectangle = new Rectangle(3, 3);
    renderer.setSeriesShape(0, rectangle);
    //renderer.setSeriesShapesVisible(0, true);
    renderer.setSeriesShapesVisible(0, false);
    renderer.setSeriesLinesVisible(0, true);

    renderer.setSeriesShape(1, rectangle);
    renderer.setSeriesShapesVisible(1, true);
    renderer.setSeriesLinesVisible(1, false);

    Paint[] paints = new Paint[] { Color.red, Color.blue };
    renderer.setSeriesPaint(0, paints[0]);
    //renderer.setSeriesPaint(1, paints[1]);

    final XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer();
    renderer2.setSeriesPaint(0, paints[1]);
    renderer2.setSeriesShapesVisible(0, false);
    renderer2.setSeriesLinesVisible(0, true);

    // Stroke is part of Java Swing ...
    //renderer2.setBaseStroke( new Stroke( ... ) );

    double ymax;
    if (maxdB < 10) {
        ymax = 10.;
    } else {
        ymax = maxdB + 2;
        ;
    }

    final NumberAxis verticalAxis = new NumberAxis("Spec Amp (dB)");
    verticalAxis.setRange(new Range(-40, ymax));
    verticalAxis.setTickUnit(new NumberTickUnit(5));

    //final LogarithmicAxis verticalAxis = new LogarithmicAxis("Amplitude Response");
    //verticalAxis.setRange( new Range(0.01 , 10) );

    final LogarithmicAxis horizontalAxis = new LogarithmicAxis("Frequency (Hz)");
    //horizontalAxis.setRange( new Range(0.0001 , 100.5) );
    //horizontalAxis.setRange( new Range(0.00009 , 110) );
    horizontalAxis.setRange(new Range(XMIN, XMAX));

    final XYSeriesCollection seriesCollection = new XYSeriesCollection();
    seriesCollection.addSeries(series1);
    seriesCollection.addSeries(series1b);

    final XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, null, verticalAxis, renderer);
    //final XYPlot xyplot = new XYPlot((XYDataset)seriesCollection, horizontalAxis, verticalAxis, renderer);

    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.black);
    xyplot.setDomainGridlinePaint(Color.black);

    final NumberAxis phaseAxis = new NumberAxis("Phase (Deg)");
    phaseAxis.setRange(new Range(-180, 180));
    phaseAxis.setTickUnit(new NumberTickUnit(30));
    final XYSeriesCollection seriesCollection2 = new XYSeriesCollection();
    seriesCollection2.addSeries(series2);
    seriesCollection2.addSeries(series2b);
    final XYPlot xyplot2 = new XYPlot((XYDataset) seriesCollection2, null, phaseAxis, renderer2);

    //CombinedXYPlot combinedPlot = new CombinedXYPlot( horizontalAxis, CombinedXYPlot.VERTICAL );
    CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis);
    combinedPlot.add(xyplot, 1);
    combinedPlot.add(xyplot2, 1);
    combinedPlot.setGap(15.);

    //final JFreeChart chart = new JFreeChart(xyplot);
    final JFreeChart chart = new JFreeChart(combinedPlot);
    chart.setTitle(new TextTitle(plotTitle));

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

    }
}

From source file:adams.flow.sink.JFreeChartFileWriter.java

/**
 * Executes the flow item./*from w w w  .j  a  va 2 s  .  c om*/
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
protected String doExecute() {
    String result;
    SpreadSheet sheet;
    Dataset dataset;
    JFreeChart jfreechart;
    BufferedImage image;
    BufferedImageContainer cont;
    Shape shape;
    XYPlot plot;

    result = null;

    try {
        sheet = (SpreadSheet) m_InputToken.getPayload();
        dataset = m_Dataset.generate(sheet);
        jfreechart = m_Chart.generate(dataset);
        shape = m_Shape.generate();
        jfreechart.getPlot().setBackgroundPaint(Color.WHITE);
        if (jfreechart.getPlot() instanceof XYPlot) {
            plot = (XYPlot) jfreechart.getPlot();
            plot.setDomainGridlinesVisible(true);
            plot.setDomainGridlinePaint(Color.GRAY);
            plot.setRangeGridlinesVisible(true);
            plot.setRangeGridlinePaint(Color.GRAY);
            plot.getRenderer().setSeriesPaint(0, m_PlotColor);
            if (plot.getSeriesCount() > 1)
                plot.getRenderer().setSeriesPaint(1, m_DiagonalColor);
            if (shape != null)
                plot.getRenderer().setSeriesShape(0, shape);
        }
        image = jfreechart.createBufferedImage(m_Width, m_Height);
        cont = new BufferedImageContainer();
        cont.setImage(image);
        m_Writer.write(m_OutputFile, cont);
    } catch (Exception e) {
        result = handleException("Failed to generate plot!", e);
    }

    return result;
}

From source file:net.nosleep.superanalyzer.analysis.views.GrowthView.java

private void createChart() {

    _chart = ChartFactory.createXYAreaChart(Misc.getString("LIBRARY_GROWTH"), Misc.getString("DATE"),
            Misc.getString("SONGS_IN_LIBRARY"), _dataset, PlotOrientation.VERTICAL, false, // legend
            true, // tool tips
            false // URLs
    );//from w  ww . j  a va  2s.  co  m
    XYPlot plot = (XYPlot) _chart.getPlot();
    plot.setDomainPannable(true);
    ValueAxis domainAxis = new DateAxis(Misc.getString("TIME"));
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    plot.setDomainAxis(domainAxis);
    plot.setForegroundAlpha(0.75f);

    XYItemRenderer renderer = plot.getRenderer();
    renderer.setBaseToolTipGenerator(
            new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                    new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("#,##0.00")));

    _chart.addSubtitle(HomePanel.createSubtitle(Misc.getString("LIBRARY_GROWTH_SUBTITLE")));

    ChartUtilities.applyCurrentTheme(_chart);
    Misc.formatChart(plot);

    plot.setDomainGridlinesVisible(false);
    plot.setRangeGridlinesVisible(false);
    renderer.setSeriesPaint(0, Theme.getColorSet()[1]);

}

From source file:ucar.unidata.idv.control.chart.PlotWrapper.java

/**
 * Utility to init xy plots//from   www.j  ava  2  s . c o m
 *
 * @param plot the plotx
 */
protected void initXYPlot(XYPlot plot) {
    plot.setBackgroundPaint(dataAreaColor);
    //        plot.setAxisOffset(new RectangleInsets(6.0, 3.0, 3.0, 3.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    plot.setDomainGridlinesVisible(domainLineState.getVisible());
    plot.setRangeGridlinesVisible(rangeLineState.getVisible());
    plot.setDomainGridlinePaint(domainLineState.getColor());
    plot.setRangeGridlinePaint(rangeLineState.getColor());
    plot.setDomainGridlineStroke(domainLineState.getStroke());
    plot.setRangeGridlineStroke(rangeLineState.getStroke());
}

From source file:msi.gama.outputs.layers.charts.ChartJFreeChartOutputHeatmap.java

@Override
public void initChart(final IScope scope, final String chartname) {
    super.initChart(scope, chartname);

    final XYPlot pp = (XYPlot) chart.getPlot();
    pp.setDomainGridlinePaint(axesColor);
    pp.setRangeGridlinePaint(axesColor);
    pp.setDomainCrosshairPaint(axesColor);
    pp.setRangeCrosshairPaint(axesColor);
    pp.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    pp.setDomainCrosshairVisible(false);
    pp.setRangeCrosshairVisible(false);// w w w  .j  a v  a  2s.  com
    pp.setRangeGridlinesVisible(false);
    pp.setDomainGridlinesVisible(false);

    pp.getDomainAxis().setAxisLinePaint(axesColor);

    pp.getDomainAxis().setTickLabelFont(getTickFont());
    pp.getDomainAxis().setLabelFont(getLabelFont());
    if (textColor != null) {
        pp.getDomainAxis().setLabelPaint(textColor);
        pp.getDomainAxis().setTickLabelPaint(textColor);
    }
    if (xtickunit > 0) {
        ((NumberAxis) pp.getDomainAxis()).setTickUnit(new NumberTickUnit(xtickunit));
    }

    pp.getRangeAxis().setAxisLinePaint(axesColor);
    pp.getRangeAxis().setLabelFont(getLabelFont());
    pp.getRangeAxis().setTickLabelFont(getTickFont());
    if (textColor != null) {
        pp.getRangeAxis().setLabelPaint(textColor);
        pp.getRangeAxis().setTickLabelPaint(textColor);
    }
    if (ytickunit > 0) {
        ((NumberAxis) pp.getRangeAxis()).setTickUnit(new NumberTickUnit(ytickunit));
    }

    // resetAutorange(scope);

    if (xlabel != null && !xlabel.isEmpty()) {
        pp.getDomainAxis().setLabel(xlabel);
    }
    if (ylabel != null && !ylabel.isEmpty()) {
        pp.getRangeAxis().setLabel(ylabel);
    }

}

From source file:org.n52.server.io.render.DiagramRenderer.java

/**
 * <pre>// ww  w. ja  v a 2  s  .  c o  m
 * dataset :=  associated to one range-axis;
 * corresponds to one observedProperty;
 * may contain multiple series;
 * series :=   corresponds to a time series for one foi
 * </pre>
 *
 * .
 *
 * @param entireCollMap
 *            the entire coll map
 * @param options
 *            the options
 * @param begin
 *            the begin
 * @param end
 *            the end
 * @param compress
 * @return the j free chart
 */
public JFreeChart renderChart(Map<String, OXFFeatureCollection> entireCollMap, DesignOptions options,
        Calendar begin, Calendar end, boolean compress) {

    DesignDescriptionList designDescriptions = buildUpDesignDescriptionList(options);

    /*** FIRST RUN ***/
    JFreeChart chart = initializeTimeSeriesChart();
    chart.setBackgroundPaint(Color.white);

    if (!this.isOverview) {
        chart.addSubtitle(new TextTitle(ConfigurationContext.COPYRIGHT, new Font(LABEL_FONT, Font.PLAIN, 9),
                Color.black, RectangleEdge.BOTTOM, HorizontalAlignment.RIGHT, VerticalAlignment.BOTTOM,
                new RectangleInsets(0, 0, 20, 20)));
    }
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setAxisOffset(new RectangleInsets(2.0, 2.0, 2.0, 2.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    plot.setDomainGridlinesVisible(options.getGrid());
    plot.setRangeGridlinesVisible(options.getGrid());

    // add additional datasets:
    DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
    dateAxis.setRange(begin.getTime(), end.getTime());
    dateAxis.setDateFormatOverride(new SimpleDateFormat());
    dateAxis.setTimeZone(end.getTimeZone());

    // add all axes
    String[] phenomenaIds = options.getAllPhenomenIds();
    // all the axis indices to map them later
    HashMap<String, Integer> axes = new HashMap<String, Integer>();
    for (int i = 0; i < phenomenaIds.length; i++) {
        axes.put(phenomenaIds[i], i);
        plot.setRangeAxis(i, new NumberAxis(phenomenaIds[i]));
    }

    // list range markers
    ArrayList<ValueMarker> referenceMarkers = new ArrayList<ValueMarker>();
    HashMap<String, double[]> referenceBounds = new HashMap<String, double[]>();

    // create all TS collections
    for (int i = 0; i < options.getProperties().size(); i++) {

        TimeseriesProperties prop = options.getProperties().get(i);

        String phenomenonId = prop.getPhenomenon();

        TimeSeriesCollection dataset = createDataset(entireCollMap, prop, phenomenonId, compress);
        dataset.setGroup(new DatasetGroup(prop.getTimeseriesId()));
        XYDataset additionalDataset = dataset;

        NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenomenonId));

        if (this.isOverview) {
            axe.setAutoRange(true);
            axe.setAutoRangeIncludesZero(false);
        } else if (prop.getAxisUpperBound() == prop.getAxisLowerBound() || prop.isAutoScale()) {
            if (prop.isZeroScaled()) {
                axe.setAutoRangeIncludesZero(true);
            } else {
                axe.setAutoRangeIncludesZero(false);
            }
        } else {
            if (prop.isZeroScaled()) {
                if (axe.getUpperBound() < prop.getAxisUpperBound()) {
                    axe.setUpperBound(prop.getAxisUpperBound());
                }
                if (axe.getLowerBound() > prop.getAxisLowerBound()) {
                    axe.setLowerBound(prop.getAxisLowerBound());
                }
            } else {
                axe.setRange(prop.getAxisLowerBound(), prop.getAxisUpperBound());
                axe.setAutoRangeIncludesZero(false);
            }
        }

        plot.setDataset(i, additionalDataset);
        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));

        // set bounds new for reference values
        if (!referenceBounds.containsKey(phenomenonId)) {
            double[] bounds = new double[] { axe.getLowerBound(), axe.getUpperBound() };
            referenceBounds.put(phenomenonId, bounds);
        } else {
            double[] bounds = referenceBounds.get(phenomenonId);
            if (bounds[0] >= axe.getLowerBound()) {
                bounds[0] = axe.getLowerBound();
            }
            if (bounds[1] <= axe.getUpperBound()) {
                bounds[1] = axe.getUpperBound();
            }
        }

        double[] bounds = referenceBounds.get(phenomenonId);
        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                Double value = prop.getRefValue(string).getValue();
                if (value <= bounds[0]) {
                    bounds[0] = value;
                } else if (value >= bounds[1]) {
                    bounds[1] = value;
                }
            }
        }

        Axis axis = prop.getAxis();
        if (axis == null) {
            axis = new Axis(axe.getUpperBound(), axe.getLowerBound());
        } else if (prop.isAutoScale()) {
            axis.setLowerBound(axe.getLowerBound());
            axis.setUpperBound(axe.getUpperBound());
            axis.setMaxY(axis.getMaxY());
            axis.setMinY(axis.getMinY());
        }
        prop.setAxisData(axis);
        this.axisMapping.put(prop.getTimeseriesId(), axis);

        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                referenceMarkers.add(new ValueMarker(prop.getRefValue(string).getValue(),
                        Color.decode(prop.getRefValue(string).getColor()),
                        new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f)));
            }
        }

        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));
    }

    for (ValueMarker valueMarker : referenceMarkers) {
        plot.addRangeMarker(valueMarker);
    }

    // show actual time
    ValueMarker nowMarker = new ValueMarker(System.currentTimeMillis(), Color.orange,
            new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f));
    plot.addDomainMarker(nowMarker);

    if (!this.isOverview) {
        Iterator<Entry<String, double[]>> iterator = referenceBounds.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, double[]> boundsEntry = iterator.next();
            String phenId = boundsEntry.getKey();
            NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenId));
            axe.setAutoRange(true);
            // add a margin
            double marginOffset = (boundsEntry.getValue()[1] - boundsEntry.getValue()[0]) / 25;
            boundsEntry.getValue()[0] -= marginOffset;
            boundsEntry.getValue()[1] += marginOffset;
            axe.setRange(boundsEntry.getValue()[0], boundsEntry.getValue()[1]);
        }
    }

    /**** SECOND RUN ***/

    // set domain axis labels:
    plot.getDomainAxis().setLabelFont(label);
    plot.getDomainAxis().setLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setTickLabelFont(tickLabelDomain);
    plot.getDomainAxis().setTickLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setLabel(designDescriptions.getDomainAxisLabel());

    // define the design for each series:
    for (int datasetIndex = 0; datasetIndex < plot.getDatasetCount(); datasetIndex++) {
        TimeSeriesCollection dataset = (TimeSeriesCollection) plot.getDataset(datasetIndex);

        for (int seriesIndex = 0; seriesIndex < dataset.getSeriesCount(); seriesIndex++) {

            String timeseriesId = (String) dataset.getSeries(seriesIndex).getKey();
            RenderingDesign dd = designDescriptions.get(timeseriesId);

            if (dd != null) {

                // LINESTYLE:
                String lineStyle = dd.getLineStyle();
                int width = dd.getLineWidth();
                if (this.isOverview) {
                    width = width / 2;
                    width = (width == 0) ? 1 : width;
                }
                // "1" is lineStyle "line"
                if (lineStyle.equalsIgnoreCase(LINE)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, false);
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                }
                // "2" is lineStyle "area"
                else if (lineStyle.equalsIgnoreCase(AREA)) {
                    plot.setRenderer(datasetIndex, new XYAreaRenderer());
                }
                // "3" is lineStyle "dotted"
                else if (lineStyle.equalsIgnoreCase(DOTTED)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(false, true);
                    ren.setShape(new Ellipse2D.Double(-width, -width, 2 * width, 2 * width));
                    plot.setRenderer(datasetIndex, ren);

                }
                // "4" is dashed
                else if (lineStyle.equalsIgnoreCase("4")) { // dashed
                    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
                    renderer.setSeriesStroke(0, new BasicStroke(width, BasicStroke.CAP_ROUND,
                            BasicStroke.JOIN_ROUND, 1.0f, new float[] { 4.0f * width, 4.0f * width }, 0.0f));
                    plot.setRenderer(datasetIndex, renderer);
                } else if (lineStyle.equalsIgnoreCase("5")) {
                    // lines and dots
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, true);
                    int thickness = 2 * width;
                    ren.setShape(new Ellipse2D.Double(-width, -width, thickness, thickness));
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                } else {
                    // default is lineStyle "line"
                    plot.setRenderer(datasetIndex, new XYLineAndShapeRenderer(true, false));
                }

                plot.getRenderer(datasetIndex).setSeriesPaint(seriesIndex, dd.getColor());

                // plot.getRenderer(datasetIndex).setShapesVisible(true);

                XYToolTipGenerator toolTipGenerator = StandardXYToolTipGenerator.getTimeSeriesInstance();
                XYURLGenerator urlGenerator = new MetadataInURLGenerator(designDescriptions);

                plot.getRenderer(datasetIndex).setBaseToolTipGenerator(toolTipGenerator);
                plot.getRenderer(datasetIndex).setURLGenerator(urlGenerator);

                // GRID:
                // PROBLEM: JFreeChart only allows to switch the grid on/off
                // for the whole XYPlot. And the
                // grid will always be displayed for the first series in the
                // plot. I'll always show the
                // grid.
                // --> plot.setDomainGridlinesVisible(visible)

                // RANGE AXIS LABELS:
                if (isOverview) {
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelsVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setTickMarksVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setVisible(false);
                } else {
                    plot.getRangeAxisForDataset(datasetIndex).setLabelFont(label);
                    plot.getRangeAxisForDataset(datasetIndex).setLabelPaint(LABEL_COLOR);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelFont(tickLabelDomain);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelPaint(LABEL_COLOR);
                    StringBuilder unitOfMeasure = new StringBuilder();
                    unitOfMeasure.append(dd.getPhenomenon().getLabel());
                    String uomLabel = dd.getUomLabel();
                    if (uomLabel != null && !uomLabel.isEmpty()) {
                        unitOfMeasure.append(" (").append(uomLabel).append(")");
                    }
                    plot.getRangeAxisForDataset(datasetIndex).setLabel(unitOfMeasure.toString());
                }
            }
        }
    }
    return chart;
}

From source file:projects.wdlf47tuc.ProcessAllSwathcal.java

/**
 * Plots the CMD using the existing dataset. Used whenever chart annotations change, without the
 * underlying plot data changing. This method identifies all sources lying within the boxed region
 * and loads them into the secondary list {@link #boxedSources}.
 * //from  w w  w  .j  a va  2s  . c  o  m
 * @param allSources
 *    The {@link Source}s to plot
 * @return
 *    A JFreeChart presenting the colour-magnitude diagram for the current selection criteria and colours.
 */
private JFreeChart plotCmd() {

    XYSeries outside = new XYSeries("Outside");
    XYSeries inside = new XYSeries("Inside");

    // Use a Path2D.Double instance to determine polygon intersection
    Path2D.Double path = new Path2D.Double();
    boxedSources.clear();

    boolean performBoxSelection = (points.size() > 2);

    if (performBoxSelection) {
        // Initialise Path2D object
        path.moveTo(points.get(0)[0], points.get(0)[1]);
        for (double[] point : points) {
            path.lineTo(point[0], point[1]);
        }
    }

    for (Source source : selectedSources) {
        double magnitude = source.getMag(magFilter);
        double col1 = source.getMag(col1Filter);
        double col2 = source.getMag(col2Filter);

        double x = col1 - col2;
        double y = magnitude;

        if (performBoxSelection) {
            Point2D.Double point = new Point2D.Double(x, y);
            if (path.contains(point)) {
                inside.add(x, y);
                boxedSources.add(source);
            } else {
                outside.add(x, y);
            }
        } else {
            outside.add(x, y);
        }
    }

    final XYSeriesCollection data = new XYSeriesCollection();
    data.addSeries(outside);
    data.addSeries(inside);

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    renderer.setSeriesLinesVisible(0, false);
    renderer.setSeriesShapesVisible(0, true);
    renderer.setSeriesShape(0, new Ellipse2D.Float(-0.5f, -0.5f, 1, 1));
    renderer.setSeriesPaint(0, ChartColor.BLACK);

    renderer.setSeriesLinesVisible(1, false);
    renderer.setSeriesShapesVisible(1, true);
    renderer.setSeriesShape(1, new Ellipse2D.Float(-0.5f, -0.5f, 1, 1));
    renderer.setSeriesPaint(1, ChartColor.RED);

    NumberAxis xAxis = new NumberAxis(col1Filter.toString() + " - " + col2Filter.toString());
    xAxis.setRange(getXRange());

    NumberAxis yAxis = new NumberAxis(magFilter.toString());
    yAxis.setRange(getYRange());
    yAxis.setInverted(true);

    // Configure plot
    XYPlot xyplot = new XYPlot(data, xAxis, yAxis, renderer);
    xyplot.setBackgroundPaint(Color.lightGray);
    xyplot.setDomainGridlinePaint(Color.white);
    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.white);

    // Specify selection box, if points have been specified
    if (!points.isEmpty()) {

        double[] coords = new double[points.size() * 2];

        for (int i = 0; i < points.size(); i++) {
            double[] point = points.get(i);
            coords[2 * i + 0] = point[0];
            coords[2 * i + 1] = point[1];
        }
        XYPolygonAnnotation box = new XYPolygonAnnotation(coords, new BasicStroke(2.0f), Color.BLUE);
        xyplot.addAnnotation(box);
    }

    // Configure chart
    JFreeChart chart = new JFreeChart("47 Tuc CMD", xyplot);
    chart.setBackgroundPaint(Color.white);
    chart.setTitle("47 Tuc colour-magnitude diagram");
    chart.removeLegend();

    return chart;
}

From source file:projects.wdlf47tuc.ProcessAllSwathcal.java

/**
 * Computes the luminosity function for the current boxed region and plots it in a JFrame.
 * Also prints out the coordinates of the selection box vertices and the luminosity function
 * quantities./*w  ww.ja v  a  2s .c  o m*/
 * 
 * @param sources
 *    The {@link Source}s to compute the luminosity function for.
 */
private void computeAndPlotLuminosityFunction(List<Source> sources) {

    // Print out coordinates of selection box corners
    System.out.println("# Coordinates of selection box corners:");
    System.out.println("# (" + col1Filter + "-" + col2Filter + ")\t" + magFilter);
    for (double[] point : points) {
        System.out.println("# " + point[0] + "\t" + point[1]);
    }
    System.out.println("# Luminosity function:");
    System.out.println("# Mag.\tN\tsigN");

    double magBinWidth = 0.5;

    // Get the range of the data
    double mMin = Double.MAX_VALUE;
    double mMax = -Double.MAX_VALUE;
    for (Source source : sources) {
        double mag = source.getMag(magFilter) - mu;
        mMin = Math.min(mMin, mag);
        mMax = Math.max(mMax, mag);
    }

    // Quantize this to a whole number
    mMin = Math.floor(mMin);
    mMax = Math.ceil(mMax);

    int nBins = (int) Math.rint((mMax - mMin) / magBinWidth);

    // Array to accumulate all objects in each bin
    int[] n = new int[nBins];

    for (Source source : sources) {
        double mag = source.getMag(magFilter) - mu;
        // Bin number
        int bin = (int) Math.floor((mag - mMin) / magBinWidth);
        n[bin]++;
    }

    YIntervalSeries luminosityFunction = new YIntervalSeries("Luminosity Function");

    for (int i = 0; i < nBins; i++) {
        // Bin centre
        double x = mMin + i * magBinWidth + 0.5 * magBinWidth;
        double y = n[i];
        double yErr = n[i] > 0 ? Math.sqrt(y) : 0;
        luminosityFunction.add(x, y, y - yErr, y + yErr);
        System.out.println(x + "\t" + y + "\t" + yErr);
    }

    final YIntervalSeriesCollection data = new YIntervalSeriesCollection();
    data.addSeries(luminosityFunction);

    XYErrorRenderer renderer = new XYErrorRenderer();
    renderer.setSeriesLinesVisible(0, true);
    renderer.setSeriesShapesVisible(0, true);
    renderer.setSeriesShape(0, new Ellipse2D.Float(-1f, -1f, 2, 2));
    renderer.setSeriesPaint(0, ChartColor.BLACK);

    NumberAxis xAxis = new NumberAxis("Absolute Magnitude (" + magFilter.toString() + ")");
    xAxis.setAutoRange(true);
    xAxis.setAutoRangeIncludesZero(false);

    NumberAxis yAxis = new NumberAxis("N");
    yAxis.setAutoRange(true);
    yAxis.setAutoRangeIncludesZero(true);

    // Configure plot
    XYPlot xyplot = new XYPlot(data, xAxis, yAxis, renderer);
    xyplot.setBackgroundPaint(Color.lightGray);
    xyplot.setDomainGridlinePaint(Color.white);
    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.white);

    // Configure chart
    JFreeChart chart = new JFreeChart("Luminosity Function", xyplot);
    chart.setBackgroundPaint(Color.white);
    chart.setTitle("47 Tuc luminosity function");
    chart.removeLegend();

    final ChartPanel lfChartPanel = new ChartPanel(chart);

    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame tester = new JFrame();
            tester.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            tester.setLayout(new BorderLayout());
            tester.add(lfChartPanel, BorderLayout.CENTER);
            tester.pack();
            tester.setVisible(true);
        }
    });

}

From source file:org.n52.server.sos.render.DiagramRenderer.java

/**
 * <pre>//from www.j a v a2  s  . c o  m
 * dataset :=  associated to one range-axis;
 * corresponds to one observedProperty;
 * may contain multiple series;
 * series :=   corresponds to a time series for one foi
 * </pre>
 * 
 * .
 * 
 * @param entireCollMap
 *            the entire coll map
 * @param options
 *            the options
 * @param begin
 *            the begin
 * @param end
 *            the end
 * @param compress
 * @return the j free chart
 */
public JFreeChart renderChart(Map<String, OXFFeatureCollection> entireCollMap, DesignOptions options,
        Calendar begin, Calendar end, boolean compress) {

    DesignDescriptionList designDescriptions = buildUpDesignDescriptionList(options);

    /*** FIRST RUN ***/
    JFreeChart chart = initializeTimeSeriesChart();
    chart.setBackgroundPaint(Color.white);

    if (!this.isOverview) {
        chart.addSubtitle(new TextTitle(ConfigurationContext.COPYRIGHT, new Font(LABEL_FONT, Font.PLAIN, 9),
                Color.black, RectangleEdge.BOTTOM, HorizontalAlignment.RIGHT, VerticalAlignment.BOTTOM,
                new RectangleInsets(0, 0, 20, 20)));
    }
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setAxisOffset(new RectangleInsets(2.0, 2.0, 2.0, 2.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    plot.setDomainGridlinesVisible(options.getGrid());
    plot.setRangeGridlinesVisible(options.getGrid());

    // add additional datasets:
    DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
    dateAxis.setRange(begin.getTime(), end.getTime());
    dateAxis.setDateFormatOverride(new SimpleDateFormat());

    // add all axes
    String[] phenomenaIds = options.getAllPhenomenIds();
    // all the axis indices to map them later
    HashMap<String, Integer> axes = new HashMap<String, Integer>();
    for (int i = 0; i < phenomenaIds.length; i++) {
        axes.put(phenomenaIds[i], i);
        plot.setRangeAxis(i, new NumberAxis(phenomenaIds[i]));
    }

    // list range markers
    ArrayList<ValueMarker> referenceMarkers = new ArrayList<ValueMarker>();
    HashMap<String, double[]> referenceBounds = new HashMap<String, double[]>();

    // create all TS collections
    for (int i = 0; i < options.getProperties().size(); i++) {

        TimeseriesProperties prop = options.getProperties().get(i);

        String phenomenonId = prop.getPhenomenon();

        TimeSeriesCollection dataset = createDataset(entireCollMap, prop, phenomenonId, compress);
        dataset.setGroup(new DatasetGroup(prop.getTimeseriesId()));
        XYDataset additionalDataset = dataset;

        NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenomenonId));

        if (this.isOverview) {
            axe.setAutoRange(true);
            axe.setAutoRangeIncludesZero(false);
        } else if (prop.getAxisUpperBound() == prop.getAxisLowerBound() || prop.isAutoScale()) {
            if (prop.isZeroScaled()) {
                axe.setAutoRangeIncludesZero(true);
            } else {
                axe.setAutoRangeIncludesZero(false);
            }
        } else {
            if (prop.isZeroScaled()) {
                if (axe.getUpperBound() < prop.getAxisUpperBound()) {
                    axe.setUpperBound(prop.getAxisUpperBound());
                }
                if (axe.getLowerBound() > prop.getAxisLowerBound()) {
                    axe.setLowerBound(prop.getAxisLowerBound());
                }
            } else {
                axe.setRange(prop.getAxisLowerBound(), prop.getAxisUpperBound());
                axe.setAutoRangeIncludesZero(false);
            }
        }

        plot.setDataset(i, additionalDataset);
        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));

        // set bounds new for reference values
        if (!referenceBounds.containsKey(phenomenonId)) {
            double[] bounds = new double[] { axe.getLowerBound(), axe.getUpperBound() };
            referenceBounds.put(phenomenonId, bounds);
        } else {
            double[] bounds = referenceBounds.get(phenomenonId);
            if (bounds[0] >= axe.getLowerBound()) {
                bounds[0] = axe.getLowerBound();
            }
            if (bounds[1] <= axe.getUpperBound()) {
                bounds[1] = axe.getUpperBound();
            }
        }

        double[] bounds = referenceBounds.get(phenomenonId);
        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                Double value = prop.getRefValue(string).getValue();
                if (value <= bounds[0]) {
                    bounds[0] = value;
                } else if (value >= bounds[1]) {
                    bounds[1] = value;
                }
            }
        }

        Axis axis = prop.getAxis();
        if (axis == null) {
            axis = new Axis(axe.getUpperBound(), axe.getLowerBound());
        } else if (prop.isAutoScale()) {
            axis.setLowerBound(axe.getLowerBound());
            axis.setUpperBound(axe.getUpperBound());
            axis.setMaxY(axis.getMaxY());
            axis.setMinY(axis.getMinY());
        }
        prop.setAxisData(axis);
        this.axisMapping.put(prop.getTimeseriesId(), axis);

        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                referenceMarkers.add(new ValueMarker(prop.getRefValue(string).getValue(),
                        Color.decode(prop.getRefValue(string).getColor()),
                        new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f)));
            }
        }

        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));
    }

    for (ValueMarker valueMarker : referenceMarkers) {
        plot.addRangeMarker(valueMarker);
    }

    // show actual time
    ValueMarker nowMarker = new ValueMarker(System.currentTimeMillis(), Color.orange,
            new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f));
    plot.addDomainMarker(nowMarker);

    if (!this.isOverview) {
        Iterator<Entry<String, double[]>> iterator = referenceBounds.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, double[]> boundsEntry = iterator.next();
            String phenId = boundsEntry.getKey();
            NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenId));
            axe.setAutoRange(true);
            // add a margin 
            double marginOffset = (boundsEntry.getValue()[1] - boundsEntry.getValue()[0]) / 25;
            boundsEntry.getValue()[0] -= marginOffset;
            boundsEntry.getValue()[1] += marginOffset;
            axe.setRange(boundsEntry.getValue()[0], boundsEntry.getValue()[1]);
        }
    }

    /**** SECOND RUN ***/

    // set domain axis labels:
    plot.getDomainAxis().setLabelFont(label);
    plot.getDomainAxis().setLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setTickLabelFont(tickLabelDomain);
    plot.getDomainAxis().setTickLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setLabel(designDescriptions.getDomainAxisLabel());

    // define the design for each series:
    for (int datasetIndex = 0; datasetIndex < plot.getDatasetCount(); datasetIndex++) {
        TimeSeriesCollection dataset = (TimeSeriesCollection) plot.getDataset(datasetIndex);

        for (int seriesIndex = 0; seriesIndex < dataset.getSeriesCount(); seriesIndex++) {

            String timeseriesId = (String) dataset.getSeries(seriesIndex).getKey();
            RenderingDesign dd = designDescriptions.get(timeseriesId);

            if (dd != null) {

                // LINESTYLE:
                String lineStyle = dd.getLineStyle();
                int width = dd.getLineWidth();
                if (this.isOverview) {
                    width = width / 2;
                    width = (width == 0) ? 1 : width;
                }
                // "1" is lineStyle "line"
                if (lineStyle.equalsIgnoreCase(LINE)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, false);
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                }
                // "2" is lineStyle "area"
                else if (lineStyle.equalsIgnoreCase(AREA)) {
                    plot.setRenderer(datasetIndex, new XYAreaRenderer());
                }
                // "3" is lineStyle "dotted"
                else if (lineStyle.equalsIgnoreCase(DOTTED)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(false, true);
                    ren.setShape(new Ellipse2D.Double(-width, -width, 2 * width, 2 * width));
                    plot.setRenderer(datasetIndex, ren);

                }
                // "4" is dashed
                else if (lineStyle.equalsIgnoreCase("4")) {
                    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
                    renderer.setSeriesStroke(0, new BasicStroke(width, BasicStroke.CAP_ROUND,
                            BasicStroke.JOIN_ROUND, 1.0f, new float[] { 4.0f * width, 4.0f * width }, 0.0f));
                    plot.setRenderer(datasetIndex, renderer);
                } else if (lineStyle.equalsIgnoreCase("5")) {
                    // lines and dots
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, true);
                    int thickness = 2 * width;
                    ren.setShape(new Ellipse2D.Double(-width, -width, thickness, thickness));
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                } else {
                    // default is lineStyle "line"
                    plot.setRenderer(datasetIndex, new XYLineAndShapeRenderer(true, false));
                }

                plot.getRenderer(datasetIndex).setSeriesPaint(seriesIndex, dd.getColor());

                // plot.getRenderer(datasetIndex).setShapesVisible(true);

                XYToolTipGenerator toolTipGenerator = StandardXYToolTipGenerator.getTimeSeriesInstance();
                XYURLGenerator urlGenerator = new MetadataInURLGenerator(designDescriptions);

                plot.getRenderer(datasetIndex).setBaseToolTipGenerator(toolTipGenerator);
                plot.getRenderer(datasetIndex).setURLGenerator(urlGenerator);

                // GRID:
                // PROBLEM: JFreeChart only allows to switch the grid on/off
                // for the whole XYPlot. And the
                // grid will always be displayed for the first series in the
                // plot. I'll always show the
                // grid.
                // --> plot.setDomainGridlinesVisible(visible)

                // RANGE AXIS LABELS:
                if (isOverview) {
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelsVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setTickMarksVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setVisible(false);
                } else {
                    plot.getRangeAxisForDataset(datasetIndex).setLabelFont(label);
                    plot.getRangeAxisForDataset(datasetIndex).setLabelPaint(LABEL_COLOR);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelFont(tickLabelDomain);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelPaint(LABEL_COLOR);
                    StringBuilder unitOfMeasure = new StringBuilder();
                    unitOfMeasure.append(dd.getPhenomenon().getLabel());
                    String uomLabel = dd.getUomLabel();
                    if (uomLabel != null && !uomLabel.isEmpty()) {
                        unitOfMeasure.append(" (").append(uomLabel).append(")");
                    }
                    plot.getRangeAxisForDataset(datasetIndex).setLabel(unitOfMeasure.toString());
                }
            }
        }
    }
    return chart;
}

From source file:be.nbb.demetra.dfm.output.simulation.RealTimePerspGraphView.java

private void configureAxis(XYPlot plot, int start, int end) {
    int nb = graphs_.size();
    List<String> names = new ArrayList<>();
    for (int i = start; i <= end; i++) {
        names.add(periods.get(i).toString());
    }// www  .  j a  v  a  2  s . c o m

    NumberAxis xAxis = new NumberAxis();
    xAxis.setTickLabelPaint(Color.GRAY);
    xAxis.setTickUnit(new MyTickUnit(names));
    xAxis.setRange(-0.5, nb - 0.5);
    xAxis.setVerticalTickLabels(true);
    plot.setDomainAxis(xAxis);
    plot.setDomainGridlinesVisible(false);
    NumberAxis yaxis = new NumberAxis();
    rescaleAxis(yaxis);
    yaxis.configure();
    plot.setRangeAxis(yaxis);

    for (int i = 0; i < nb; i++) {
        ValueMarker marker = new ValueMarker(i + 0.5);
        marker.setStroke(MARKER_STROKE);
        marker.setPaint(MARKER_PAINT);
        marker.setAlpha(MARKER_ALPHA);
        plot.addDomainMarker(marker);
    }
}