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

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

Introduction

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

Prototype

public ValueAxis getRangeAxis(int index) 

Source Link

Document

Returns the range axis with the specified index, or null if there is no axis with that index.

Usage

From source file:nu.nethome.home.items.web.GraphServlet.java

/**
* This is the main enterence point of the class. This is called when a http request is
* routed to this servlet.//  w w w. jav  a2s.  co  m
*/
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ServletOutputStream p = res.getOutputStream();
    Date startTime = null;
    Date stopTime = null;

    // Analyse arguments
    String fileName = req.getParameter("file");
    if (fileName != null)
        fileName = getFullFileName(fromURL(fileName));
    String startTimeString = req.getParameter("start");
    String stopTimeString = req.getParameter("stop");
    try {
        if (startTimeString != null) {
            startTime = m_Format.parse(startTimeString);
        }
        if (stopTimeString != null) {
            stopTime = m_Format.parse(stopTimeString);
        }
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
    String look = req.getParameter("look");
    if (look == null)
        look = "";

    TimeSeries timeSeries = new TimeSeries("Data", Minute.class);

    // Calculate time window
    Calendar cal = Calendar.getInstance();
    Date currentTime = cal.getTime();
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    Date startOfDay = cal.getTime();
    cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    Date startOfWeek = cal.getTime();
    cal.set(Calendar.DAY_OF_MONTH, 1);
    Date startOfMonth = cal.getTime();
    cal.set(Calendar.MONTH, Calendar.JANUARY);
    Date startOfYear = cal.getTime();

    // if (startTime == null) startTime = startOfWeek;
    if (stopTime == null)
        stopTime = currentTime;
    if (startTime == null)
        startTime = new Date(stopTime.getTime() - 1000L * 60L * 60L * 24L * 2L);

    try {
        // Open the data file
        File logFile = new File(fileName);
        Scanner fileScanner = new Scanner(logFile);
        Long startTimeMs = startTime.getTime();
        Long month = 1000L * 60L * 60L * 24L * 30L;
        boolean doOptimize = true;
        boolean justOptimized = false;
        try {
            while (fileScanner.hasNext()) {
                try {
                    // Get next log entry
                    String line = fileScanner.nextLine();
                    if (line.length() > 21) {
                        // Adapt the time format
                        String minuteTime = line.substring(0, 16).replace('.', '-');
                        // Parse the time stamp
                        Minute min = Minute.parseMinute(minuteTime);

                        // Ok, this is an ugly optimization. If the current time position in the file
                        // is more than a month (30 days) ahead of the start of the time window, we
                        // quick read two weeks worth of data, assuming that there is 4 samples per hour.
                        // This may lead to scanning past start of window if there are holes in the data
                        // series.
                        if (doOptimize && ((startTimeMs - min.getFirstMillisecond()) > month)) {
                            for (int i = 0; (i < (24 * 4 * 14)) && fileScanner.hasNext(); i++) {
                                fileScanner.nextLine();
                            }
                            justOptimized = true;
                            continue;
                        }
                        // Detect if we have scanned past the window start position just after an optimization scan.
                        // If this is the case it may be because of the optimization. In that case we have to switch 
                        // optimization off and start over.
                        if ((min.getFirstMillisecond() > startTimeMs) && doOptimize && justOptimized) {
                            logFile = new File(fileName);
                            fileScanner = new Scanner(logFile);
                            doOptimize = false;
                            continue;
                        }
                        justOptimized = false;
                        // Check if value is within time window
                        if ((min.getFirstMillisecond() > startTimeMs)
                                && (min.getFirstMillisecond() < stopTime.getTime())) {
                            // Parse the value
                            double value = Double.parseDouble((line.substring(20)).replace(',', '.'));
                            // Add the entry
                            timeSeries.add(min, value);
                            doOptimize = false;
                        }
                    }
                } catch (SeriesException se) {
                    // Bad entry, for example due to duplicates at daylight saving time switch
                } catch (NumberFormatException nfe) {
                    // Bad number format in a line, try to continue
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            fileScanner.close();
        }
    } catch (FileNotFoundException f) {
        System.out.println(f.toString());
    }

    // Create a collection for plotting
    TimeSeriesCollection data = new TimeSeriesCollection();
    data.addSeries(timeSeries);

    JFreeChart chart;

    int xSize = 750;
    int ySize = 450;
    // Customize colors and look of the Graph.
    if (look.equals("mobtemp")) {
        // Look for the mobile GUI
        chart = ChartFactory.createTimeSeriesChart(null, null, null, data, false, false, false);
        XYPlot plot = chart.getXYPlot();
        ValueAxis timeAxis = plot.getDomainAxis();
        timeAxis.setAxisLineVisible(false);
        ValueAxis valueAxis = plot.getRangeAxis(0);
        valueAxis.setAxisLineVisible(false);
        xSize = 175;
        ySize = 180;
    } else {
        // Create a Chart with time range as heading
        SimpleDateFormat localFormat = new SimpleDateFormat();
        String heading = localFormat.format(startTime) + " - " + localFormat.format(stopTime);
        chart = ChartFactory.createTimeSeriesChart(heading, null, null, data, false, false, false);

        Paint background = new Color(0x9D8140);
        chart.setBackgroundPaint(background);
        TextTitle title = chart.getTitle(); // fix title
        Font titleFont = title.getFont();
        titleFont = titleFont.deriveFont(Font.PLAIN, (float) 14.0);
        title.setFont(titleFont);
        title.setPaint(Color.darkGray);
        XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(background);
        plot.setDomainGridlinePaint(Color.darkGray);
        ValueAxis timeAxis = plot.getDomainAxis();
        timeAxis.setAxisLineVisible(false);
        ValueAxis valueAxis = plot.getRangeAxis(0);
        valueAxis.setAxisLineVisible(false);
        plot.setRangeGridlinePaint(Color.darkGray);
        XYItemRenderer renderer = plot.getRenderer(0);
        renderer.setSeriesPaint(0, Color.darkGray);
        xSize = 750;
        ySize = 450;
    }

    try {
        res.setContentType("image/png");
        res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
        res.setHeader("Pragma", "no-cache");
        res.setStatus(HttpServletResponse.SC_OK);
        ChartUtilities.writeChartAsPNG(p, chart, xSize, ySize);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");
    }

    p.flush();
    p.close();
    return;
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.XYAreaLineChartExpression.java

protected void configureChart(final JFreeChart chart) {
    super.configureChart(chart);

    final XYPlot plot = chart.getXYPlot();

    if (isSharedRangeAxis() == false) {
        final ValueAxis linesAxis = plot.getRangeAxis(1);
        if (linesAxis instanceof NumberAxis) {
            final NumberAxis numberAxis = (NumberAxis) linesAxis;
            numberAxis.setAutoRangeIncludesZero(isLineAxisIncludesZero());
            numberAxis.setAutoRangeStickyZero(isLineAxisStickyZero());

            if (getLinePeriodCount() > 0) {
                if (getLineTicksLabelFormat() != null) {
                    final FastDecimalFormat formatter = new FastDecimalFormat(getLineTicksLabelFormat(),
                            getResourceBundleFactory().getLocale());
                    numberAxis.setTickUnit(new FastNumberTickUnit(getLinePeriodCount(), formatter));
                } else {
                    numberAxis.setTickUnit(new FastNumberTickUnit(getLinePeriodCount()));
                }//from  w  w w  .ja v  a 2 s .  co m
            } else {
                if (getLineTicksLabelFormat() != null) {
                    final DecimalFormat formatter = new DecimalFormat(getLineTicksLabelFormat(),
                            new DecimalFormatSymbols(getResourceBundleFactory().getLocale()));
                    numberAxis.setNumberFormatOverride(formatter);
                }
            }
        } else if (linesAxis instanceof DateAxis) {
            final DateAxis numberAxis = (DateAxis) linesAxis;

            if (getLinePeriodCount() > 0 && getLineTimePeriod() != null) {
                if (getLineTicksLabelFormat() != null) {
                    final SimpleDateFormat formatter = new SimpleDateFormat(getLineTicksLabelFormat(),
                            new DateFormatSymbols(getResourceBundleFactory().getLocale()));
                    numberAxis.setTickUnit(new DateTickUnit(getDateUnitAsInt(getLineTimePeriod()),
                            (int) getLinePeriodCount(), formatter));
                } else {
                    numberAxis.setTickUnit(new DateTickUnit(getDateUnitAsInt(getLineTimePeriod()),
                            (int) getLinePeriodCount()));
                }
            } else if (getRangeTickFormatString() != null) {
                final SimpleDateFormat formatter = new SimpleDateFormat(getRangeTickFormatString(),
                        new DateFormatSymbols(getResourceBundleFactory().getLocale()));
                numberAxis.setDateFormatOverride(formatter);
            }
        }

        if (linesAxis != null) {
            final Font labelFont = Font.decode(getLabelFont());
            linesAxis.setLabelFont(labelFont);
            linesAxis.setTickLabelFont(labelFont);

            if (getLineTitleFont() != null) {
                linesAxis.setLabelFont(getLineTitleFont());
            }
            if (getLineTickFont() != null) {
                linesAxis.setTickLabelFont(getLineTickFont());
            }
            final int level = getRuntime().getProcessingContext().getCompatibilityLevel();
            if (ClassicEngineBoot.isEnforceCompatibilityFor(level, 3, 8)) {
                final double lineRangeMinimumVal = lineRangeMinimum == null ? 0 : lineRangeMinimum;
                final double lineRangeMaximumVal = lineRangeMaximum == null ? 0 : lineRangeMaximum;
                if (lineRangeMinimum != null) {
                    linesAxis.setLowerBound(getLineRangeMinimum());
                }
                if (lineRangeMaximum != null) {
                    linesAxis.setUpperBound(getRangeMaximum());
                }
                if (lineRangeMinimumVal == 0 && lineRangeMaximumVal == 1) {
                    linesAxis.setLowerBound(0);
                    linesAxis.setUpperBound(1);
                    linesAxis.setAutoRange(true);
                }
            } else {
                if (lineRangeMinimum != null) {
                    linesAxis.setLowerBound(lineRangeMinimum);
                }
                if (lineRangeMaximum != null) {
                    linesAxis.setUpperBound(lineRangeMaximum);
                }
                linesAxis.setAutoRange(isLineAxisAutoRange());
            }
        }
    }

    final XYLineAndShapeRenderer linesRenderer = (XYLineAndShapeRenderer) plot.getRenderer(1);
    if (linesRenderer != null) {
        //set stroke with line width
        linesRenderer.setStroke(translateLineStyle(getLineWidth(), getLineStyle()));
        //hide shapes on line
        linesRenderer.setShapesVisible(isMarkersVisible());
        linesRenderer.setBaseShapesFilled(isMarkersVisible());

        //set colors for each line
        for (int i = 0; i < lineSeriesColor.size(); i++) {
            final String s = (String) lineSeriesColor.get(i);
            linesRenderer.setSeriesPaint(i, parseColorFromString(s));
        }
    }
}

From source file:edu.wisc.ssec.mcidasv.control.McIDASVHistogramWrapper.java

/**
 * reset the histogram to its previous range
 *///from  ww w  .  j  av  a2s  .c  o  m
public void resetPlot() {
    if (chart == null) {
        return;
    }
    if (!(chart.getPlot() instanceof XYPlot)) {
        return;
    }
    XYPlot plot = (XYPlot) chart.getPlot();
    int rcnt = plot.getRangeAxisCount();
    for (int i = 0; i < rcnt; i++) {
        ValueAxis axis = plot.getRangeAxis(i);
        axis.setAutoRange(true);
    }
    int dcnt = plot.getDomainAxisCount();
    for (int i = 0; i < dcnt; i++) {
        ValueAxis axis = plot.getDomainAxis(i);
        try {
            axis.setRange(low, high);
        } catch (Exception e) {
            logger.warn("jfreechart does not like ranges to be high -> low", e);
        }
    }
}

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

@Override
public void getModelCoordinatesInfo(final int xOnScreen, final int yOnScreen, final IDisplaySurface g,
        final Point positionInPixels, final StringBuilder sb) {
    final int x = xOnScreen - positionInPixels.x;
    final int y = yOnScreen - positionInPixels.y;
    final ChartEntity entity = info.getEntityCollection().getEntity(x, y);
    // getChart().handleClick(x, y, info);
    if (entity instanceof XYItemEntity) {
        final XYDataset data = ((XYItemEntity) entity).getDataset();
        final int index = ((XYItemEntity) entity).getItem();
        final int series = ((XYItemEntity) entity).getSeriesIndex();
        final double xx = data.getXValue(series, index);
        final double yy = data.getYValue(series, index);
        final XYPlot plot = (XYPlot) getJFChart().getPlot();
        final ValueAxis xAxis = plot.getDomainAxis(series);
        final ValueAxis yAxis = plot.getRangeAxis(series);
        final boolean xInt = xx % 1 == 0;
        final boolean yInt = yy % 1 == 0;
        String xTitle = xAxis.getLabel();
        if (StringUtils.isBlank(xTitle)) {
            xTitle = "X";
        }//from   w w  w .jav  a2 s .c o  m
        String yTitle = yAxis.getLabel();
        if (StringUtils.isBlank(yTitle)) {
            yTitle = "Y";
        }
        sb.append(xTitle).append(" ").append(xInt ? (int) xx : String.format("%.2f", xx));
        sb.append(" | ").append(yTitle).append(" ").append(yInt ? (int) yy : String.format("%.2f", yy));
        return;
    } else if (entity instanceof PieSectionEntity) {
        final String title = ((PieSectionEntity) entity).getSectionKey().toString();
        final PieDataset data = ((PieSectionEntity) entity).getDataset();
        final int index = ((PieSectionEntity) entity).getSectionIndex();
        final double xx = data.getValue(index).doubleValue();
        final boolean xInt = xx % 1 == 0;
        sb.append(title).append(" ").append(xInt ? (int) xx : String.format("%.2f", xx));
        return;
    } else if (entity instanceof CategoryItemEntity) {
        final Comparable<?> columnKey = ((CategoryItemEntity) entity).getColumnKey();
        final String title = columnKey.toString();
        final CategoryDataset data = ((CategoryItemEntity) entity).getDataset();
        final Comparable<?> rowKey = ((CategoryItemEntity) entity).getRowKey();
        final double xx = data.getValue(rowKey, columnKey).doubleValue();
        final boolean xInt = xx % 1 == 0;
        sb.append(title).append(" ").append(xInt ? (int) xx : String.format("%.2f", xx));
        return;
    }
}

From source file:com.rapidminer.gui.new_plotter.gui.dialog.AddParallelLineDialog.java

/**
 * Updates the preselected y-value.//from  ww  w.  j ava  2 s  .  com
 */
private void updateYFieldValue() {
    // update preselected y value because range axis has been changed
    if (mousePosition != null) {
        Rectangle2D plotArea = engine.getChartPanel().getScreenDataArea();
        if (engine.getChartPanel().getChart().getPlot() instanceof XYPlot) {
            XYPlot plot = (XYPlot) engine.getChartPanel().getChart().getPlot();

            // calculate y value
            for (int i = 0; i < plot.getRangeAxisCount(); i++) {
                ValueAxis config = plot.getRangeAxis(i);
                if (config != null && config.getLabel() != null) {
                    if (config.getLabel()
                            .equals(String.valueOf(rangeAxisSelectionCombobox.getSelectedItem()))) {
                        double chartY = config.java2DToValue(mousePosition.getY(), plotArea,
                                plot.getRangeAxisEdge());
                        yField.setText(String.valueOf(chartY));
                    }
                }
            }
        }
    }
}

From source file:mil.tatrc.physiology.utilities.csv.plots.CSVPlotTool.java

public void formatXYPlot(JFreeChart chart, Paint bgColor) {
    XYPlot plot = (XYPlot) chart.getPlot();

    //For Scientific notation
    NumberFormat formatter = new DecimalFormat("0.######E0");

    for (int i = 0; i < plot.getDomainAxisCount(); i++) {
        plot.getDomainAxis(i).setLabelFont(largeFont);
        plot.getDomainAxis(i).setTickLabelFont(smallFont);
        plot.getDomainAxis(i).setLabelPaint(bgColor == Color.red ? Color.white : Color.black);
        plot.getDomainAxis(i).setTickLabelPaint(bgColor == Color.red ? Color.white : Color.black);
    }//  www .j  a  v a 2  s . co  m
    for (int i = 0; i < plot.getRangeAxisCount(); i++) {
        plot.getRangeAxis(i).setLabelFont(largeFont);
        plot.getRangeAxis(i).setTickLabelFont(smallFont);
        plot.getRangeAxis(i).setLabelPaint(bgColor == Color.red ? Color.white : Color.black);
        plot.getRangeAxis(i).setTickLabelPaint(bgColor == Color.red ? Color.white : Color.black);
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(i);
        rangeAxis.setNumberFormatOverride(formatter);
    }

    //White background outside of plottable area
    chart.setBackgroundPaint(bgColor);

    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.black);
    plot.setRangeGridlinePaint(Color.black);

    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    chart.getLegend().setItemFont(smallFont);
    chart.getTitle().setFont(largeFont);
    chart.getTitle().setPaint(bgColor == Color.red ? Color.white : Color.black);
}

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

/**
 * Move plot up/down.//from  ww w  . j  ava  2s .c o  m
 *
 * @param up up
 */
private void upDownPlot(boolean up) {
    if (!(plot instanceof XYPlot)) {
        return;
    }
    XYPlot xyPlot = (XYPlot) plot;

    int cnt = xyPlot.getRangeAxisCount();
    for (int i = 0; i < cnt; i++) {
        ValueAxis axis = (ValueAxis) xyPlot.getRangeAxis(i);
        org.jfree.data.Range range = axis.getRange();
        double width = range.getUpperBound() - range.getLowerBound();
        double width2 = width / 2.0;
        double step = (up ? width * 0.1 : -width * 0.1);
        axis.centerRange(range.getLowerBound() + step + width2);
    }
}