List of usage examples for org.jfree.chart.plot XYPlot setRangeAxis
public void setRangeAxis(ValueAxis axis)
From source file:org.jfree.chart.demo.XYTickLabelDemo.java
/** * When a checkbox is changed .../*from w w w . ja v a2 s. co m*/ * * @param event the event. */ public void actionPerformed(final ActionEvent event) { final ValueAxis[] axes = new ValueAxis[4]; final XYPlot plot = this.chart.getXYPlot(); axes[0] = plot.getDomainAxis(); axes[1] = plot.getRangeAxis(); axes[2] = plot.getDomainAxis(1); axes[3] = plot.getRangeAxis(1); final Object source = event.getSource(); if (source == this.symbolicAxesCheckBox) { final boolean val = this.symbolicAxesCheckBox.isSelected(); for (int i = 0; i < axes.length; i++) { ValueAxis axis = axes[i]; final String label = axis.getLabel(); final int maxTick = (int) axis.getUpperBound(); final String[] tickLabels = new String[maxTick]; final Font ft = axis.getTickLabelFont(); for (int itk = 0; itk < maxTick; itk++) { tickLabels[itk] = "Label " + itk; } axis = val ? new SymbolicAxis(label, tickLabels) : new NumberAxis(label); axis.setTickLabelFont(ft); axes[i] = axis; } plot.setDomainAxis(axes[0]); plot.setRangeAxis(axes[1]); plot.setDomainAxis(1, axes[2]); plot.setRangeAxis(1, axes[3]); } if (source == this.symbolicAxesCheckBox || source == this.verticalTickLabelsCheckBox) { final boolean val = this.verticalTickLabelsCheckBox.isSelected(); for (int i = 0; i < axes.length; i++) { axes[i].setVerticalTickLabels(val); } } else if (source == this.symbolicAxesCheckBox || source == this.horizontalPlotCheckBox) { final PlotOrientation val = this.horizontalPlotCheckBox.isSelected() ? PlotOrientation.HORIZONTAL : PlotOrientation.VERTICAL; this.chart.getXYPlot().setOrientation(val); } else if (source == this.symbolicAxesCheckBox || source == this.fontSizeTextField) { final String s = this.fontSizeTextField.getText(); if (s.length() > 0) { final float sz = Float.parseFloat(s); for (int i = 0; i < axes.length; i++) { final ValueAxis axis = axes[i]; Font ft = axis.getTickLabelFont(); ft = ft.deriveFont(sz); axis.setTickLabelFont(ft); } } } }
From source file:edu.umn.ecology.populus.plot.BasicPlotInfo.java
public ChartTheme getJFreeChartTheme() { class PopChartTheme implements ChartTheme { private BasicPlotInfo bpiRef; public PopChartTheme(BasicPlotInfo bpi) { this.bpiRef = bpi; }//from ww w . ja v a 2 s . com public void apply(JFreeChart chart) { JFCXYAdapter jfca = new JFCXYAdapter(); XYPlot plot = chart.getXYPlot(); plot.setDataset(jfca); if (isLogPlot) { plot.setRangeAxis(new LogarithmicAxis("")); } if (isFrequencies) { ValueAxis va = plot.getRangeAxis(); if (va instanceof NumberAxis) { NumberAxis na = (NumberAxis) va; na.setTickUnit(new NumberTickUnit(0.1)); } else { Logging.log("Range Axis is not NumberAxis, why?", Logging.kWarn); } } if (xMinSet) plot.getDomainAxis().setLowerBound(xAxisMin); if (xMaxSet) plot.getDomainAxis().setUpperBound(xAxisMax); if (yMinSet) plot.getRangeAxis().setLowerBound(yAxisMin); if (yMaxSet) plot.getRangeAxis().setUpperBound(yAxisMax); //TODO - just use this renderer plot.setRenderer(new ChartRendererWithOrientatedShapes(bpiRef)); XYItemRenderer r = plot.getRenderer(); // AbstractXYItemRenderer r = plot.getRenderer(); if (r instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; for (int i = 0; i < getNumSeries(); i++) { //Set Line renderer.setSeriesPaint(i, getLineColor(i)); renderer.setSeriesStroke(i, getLineStroke(i)); //Set Symbol renderer.setSeriesFillPaint(i, getSymbolColor(i)); renderer.setSeriesOutlinePaint(i, getSymbolColor(i)); Shape shape = getSymbolShape(i); if (shape != null) { renderer.setSeriesShape(i, shape); renderer.setSeriesShapesFilled(i, isSymbolOpaque(i)); renderer.setUseFillPaint(true); renderer.setUseOutlinePaint(true); renderer.setSeriesShapesVisible(i, true); } } } else if (r instanceof XYBarRenderer) { XYBarRenderer barRenderer = (XYBarRenderer) r; barRenderer.setBarPainter(new StandardXYBarPainter()); } else { Logging.log("Unknown renderer type: " + r.getClass(), Logging.kWarn); } //inner labels, used in AIDS: Therapy plot.clearAnnotations(); Enumeration<InnerLabel> e = innerLabels.elements(); while (e.hasMoreElements()) { InnerLabel lab = (InnerLabel) e.nextElement(); Logging.log("Adding " + lab.caption + " at " + lab.x + ", " + lab.y); XYTextAnnotation annotation = new XYTextAnnotation(lab.caption, lab.x, lab.y); annotation.setTextAnchor(TextAnchor.BOTTOM_CENTER); annotation.setOutlineVisible(true); plot.addAnnotation(annotation); //I actually think the annotation above is ugly. We can use one of these instead in the future, maybe... /*PointerAnnotation may look cool... * That 2.0 is the angle, randomly picked * XYPointerAnnotation annotation = new XYPointerAnnotation(lab.caption, lab.x, lab.y, 2.0); */ /* ValueMarker marker = new ValueMarker(lab.x); marker.setLabel(lab.caption); marker.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT); plot.addDomainMarker(marker); */ } //This is set for GD: AMCM if (startGridded) { plot.setDomainGridlinesVisible(true); plot.setDomainGridlinePaint(Color.BLACK); plot.setRangeGridlinesVisible(true); plot.setRangeGridlinePaint(Color.BLACK); } } } return new PopChartTheme(this); }
From source file:desmoj.extensions.grafic.util.Plotter.java
/** * Build a JPanel with plotType of a DesmoJ time-series dataset. * When allowMultipleValues is set, multiple range values of a time value are allowed. * In the opposite Case only the last range value of a time value is accepted. * In the case ts.getShowTimeSpansInReport() the data values are interpreted as * a timespan in a appropriate time unit. * @param ts DesmoJ time-series dataset * @param plotType possible Values: * Plotter.TimeSeries_ScatterPlot, * Plotter.TimeSeries_StepChart * Plotter.TimeSeries_LinePlot * @param allowMultipleValues//from w w w . ja v a 2s.c om * @return */ private JPanel getTimeSeriesPanel(TimeSeries ts, int plotType, boolean allowMultipleValues) { JFreeChart chart; TimeSeriesDataSetAdapter dataset = new TimeSeriesDataSetAdapter(ts, allowMultipleValues); switch (plotType) { case Plotter.TimeSeries_LineChart: chart = ChartFactory.createXYLineChart(ts.getName(), "Time", "Observation", dataset, PlotOrientation.VERTICAL, false, false, false); break; case Plotter.TimeSeries_ScatterPlot: chart = ChartFactory.createScatterPlot(ts.getName(), "Time", "Observation", dataset, PlotOrientation.VERTICAL, false, false, false); break; case Plotter.TimeSeries_StepChart: chart = ChartFactory.createXYStepChart(ts.getName(), "Time", "Observation", dataset, PlotOrientation.VERTICAL, false, false, false); break; default: chart = ChartFactory.createScatterPlot(ts.getName(), "Time", "Observation", dataset, PlotOrientation.VERTICAL, false, false, false); break; } if (ts.getDescription() != null) chart.setTitle(ts.getDescription()); XYPlot xyplot = (XYPlot) chart.getPlot(); xyplot.setNoDataMessage("NO DATA"); if (ts.getShowTimeSpansInReport() && !dataset.isValid()) xyplot.setNoDataMessage("NO VALID TIMESPANS"); xyplot.setDomainZeroBaselineVisible(false); xyplot.setRangeZeroBaselineVisible(false); DateAxis dateAxis = new DateAxis(); xyplot.setDomainAxis(dateAxis); this.configureDomainAxis(dateAxis); String numberLabel; if (!dataset.isValid()) numberLabel = "Unit: invalid"; else if (ts.getShowTimeSpansInReport()) numberLabel = "Unit: timespan [" + dataset.getRangeTimeUnit().name() + "]"; else if (ts.getUnit() != null) numberLabel = "Unit: [" + ts.getUnit() + "]"; else numberLabel = "Unit: unknown"; NumberAxis numberAxis = new NumberAxis(); xyplot.setRangeAxis(numberAxis); this.configureRangeAxis(numberAxis, numberLabel); XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyplot.getRenderer(); xylineandshaperenderer.setSeriesOutlinePaint(0, Color.black); xylineandshaperenderer.setUseOutlinePaint(true); ChartPanel panel = new ChartPanel(chart); panel.setVerticalAxisTrace(false); panel.setHorizontalAxisTrace(false); panel.setPopupMenu(null); panel.setDomainZoomable(false); panel.setRangeZoomable(false); return panel; }
From source file:org.pentaho.plugin.jfreereport.reportcharts.XYChartExpression.java
protected void configureLogarithmicAxis(final XYPlot plot) { if (isLogarithmicAxis()) { final LogarithmicAxis logarithmicAxis; if (isHumanReadableLogarithmicFormat()) { plot.getRenderer().setBaseItemLabelGenerator(new LogXYItemLabelGenerator()); logarithmicAxis = new ScalingLogarithmicAxis(getRangeTitle()); logarithmicAxis.setStrictValuesFlag(false); } else {/* w w w.j a va 2 s . c om*/ logarithmicAxis = new LogarithmicAxis(getRangeTitle()); logarithmicAxis.setStrictValuesFlag(false); } plot.setRangeAxis(logarithmicAxis); } }
From source file:ec.ui.view.MarginView.java
private JFreeChart createMarginViewChart() { JFreeChart result = ChartFactory.createXYLineChart("", "", "", Charts.emptyXYDataset(), PlotOrientation.VERTICAL, false, false, false); result.setPadding(TsCharts.CHART_PADDING); XYPlot plot = result.getXYPlot(); plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); LinesThickness linesThickness = LinesThickness.Thin; XYLineAndShapeRenderer main = new LineRenderer(); plot.setRenderer(MAIN_INDEX, main);/* w ww . j av a2 s . com*/ XYDifferenceRenderer difference = new XYDifferenceRenderer(); difference.setAutoPopulateSeriesPaint(false); difference.setAutoPopulateSeriesStroke(false); difference.setBaseStroke(TsCharts.getNormalStroke(linesThickness)); plot.setRenderer(DIFFERENCE_INDEX, difference); DateAxis domainAxis = new DateAxis(); domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); domainAxis.setTickLabelPaint(TsCharts.CHART_TICK_LABEL_COLOR); plot.setDomainAxis(domainAxis); NumberAxis rangeAxis = new NumberAxis(); rangeAxis.setAutoRangeIncludesZero(false); rangeAxis.setTickLabelPaint(TsCharts.CHART_TICK_LABEL_COLOR); plot.setRangeAxis(rangeAxis); return result; }
From source file:edu.fullerton.viewerplugin.SpectrumPlot.java
private ChartPanel getPanel(ArrayList<ChanDataBuffer> dbufs, boolean compact) throws WebUtilException { ChartPanel ret = null;// www. j a va2s .com try { float tfsMax = 0; for (ChanDataBuffer buf : dbufs) { ChanInfo ci = buf.getChanInfo(); float fs = ci.getRate(); tfsMax = Math.max(fs, tfsMax); } setFsMax(tfsMax); String gtitle = getTitle(dbufs, compact); int nbuf = dbufs.size(); XYSeries[] xys = new XYSeries[nbuf]; XYSeriesCollection mtds = new XYSeriesCollection(); int cnum = 0; compact = dbufs.size() > 2 ? false : compact; float bw = 1.f; for (ChanDataBuffer dbuf : dbufs) { String legend = getLegend(dbuf, compact); xys[cnum] = new XYSeries(legend); bw = calcSpectrum(xys[cnum], dbuf); mtds.addSeries(xys[cnum]); } DefaultXYDataset ds = new DefaultXYDataset(); String yLabel = pwrScale.toString(); DecimalFormat dform = new DecimalFormat("0.0###"); String xLabel; xLabel = String.format("Frequency Hz - (bw: %1$s, #fft: %2$,d, s/fft: %3$.2f, ov: %4$.2f)", dform.format(bw), nfft, secperfft, overlap); Double minx, miny, maxx, maxy; Double[] rng = new Double[4]; if (fmin <= 0) { fmin = bw; } float searchFmax = fmax; if (fmax <= 0 || fmax == Float.MAX_VALUE) { fmax = tfsMax / 2; searchFmax = tfsMax / 2 * 0.8f; } PluginSupport.getRangeLimits(mtds, rng, 2, fmin, searchFmax); minx = rng[0]; miny = rng[1]; maxx = rng[2]; maxy = rng[3]; findSmallest(mtds); int exp; if (maxy == 0. && miny == 0.) { miny = -1.; exp = 0; logYaxis = false; } else { miny = miny > 0 ? miny : smallestY; maxy = maxy > 0 ? maxy : miny * 10; exp = PluginSupport.scaleRange(mtds, miny, maxy); if (!logYaxis) { yLabel += " x 1e-" + Integer.toString(exp); } } JFreeChart chart = ChartFactory.createXYLineChart(gtitle, xLabel, yLabel, ds, PlotOrientation.VERTICAL, true, false, false); XYPlot plot = (XYPlot) chart.getPlot(); if (logYaxis) { LogAxis rangeAxis = new LogAxis(yLabel); double smallest = miny * Math.pow(10, exp); rangeAxis.setSmallestValue(smallest); rangeAxis.setMinorTickCount(9); LogAxisNumberFormat lanf = new LogAxisNumberFormat(); lanf.setExp(exp); rangeAxis.setNumberFormatOverride(lanf); rangeAxis.setRange(smallest, maxy * Math.pow(10, exp)); rangeAxis.setStandardTickUnits(LogAxis.createLogTickUnits(Locale.US)); plot.setRangeAxis(rangeAxis); plot.setRangeGridlinesVisible(true); plot.setRangeGridlinePaint(Color.BLACK); } if (logXaxis) { LogAxis domainAxis = new LogAxis(xLabel); domainAxis.setBase(2); domainAxis.setMinorTickCount(9); domainAxis.setMinorTickMarksVisible(true); domainAxis.setSmallestValue(smallestX); domainAxis.setNumberFormatOverride(new LogAxisNumberFormat()); //domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); plot.setDomainAxis(domainAxis); plot.setDomainGridlinesVisible(true); plot.setDomainGridlinePaint(Color.BLACK); } ValueAxis domainAxis = plot.getDomainAxis(); if (fmin > Float.MIN_VALUE) { domainAxis.setLowerBound(fmin); } if (fmax != Float.MAX_VALUE) { domainAxis.setUpperBound(fmax); } plot.setDomainAxis(domainAxis); plot.setDataset(0, mtds); plot.setDomainGridlinePaint(Color.DARK_GRAY); plot.setRangeGridlinePaint(Color.DARK_GRAY); // Set the line thickness XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) plot.getRenderer(); BasicStroke str = new BasicStroke(lineThickness); int n = plot.getSeriesCount(); for (int i = 0; i < n; i++) { r.setSeriesStroke(i, str); } plot.setBackgroundPaint(Color.WHITE); if (compact) { chart.removeLegend(); } ret = new ChartPanel(chart); } catch (Exception ex) { throw new WebUtilException("Creating spectrum plot" + ex.getLocalizedMessage()); } return ret; }
From source file:be.nbb.demetra.dfm.output.FactorChart.java
private JFreeChart createMarginViewChart() { JFreeChart result = ChartFactory.createXYLineChart("", "", "", Charts.emptyXYDataset(), PlotOrientation.VERTICAL, false, false, false); result.setPadding(TsCharts.CHART_PADDING); XYPlot plot = result.getXYPlot(); plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); LinesThickness linesThickness = LinesThickness.Thin; XYLineAndShapeRenderer factor = new LineRenderer(FACTOR_INDEX); plot.setRenderer(FACTOR_INDEX, factor); XYLineAndShapeRenderer filtered = new LineRenderer(FILTERED_INDEX); plot.setRenderer(FILTERED_INDEX, filtered); XYDifferenceRenderer difference = new XYDifferenceRenderer(); difference.setAutoPopulateSeriesPaint(false); difference.setAutoPopulateSeriesStroke(false); difference.setBaseStroke(TsCharts.getNormalStroke(linesThickness)); plot.setRenderer(DIFFERENCE_INDEX, difference); DateAxis domainAxis = new DateAxis(); domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); domainAxis.setTickLabelPaint(TsCharts.CHART_TICK_LABEL_COLOR); plot.setDomainAxis(domainAxis);//w w w. j av a2 s .c o m NumberAxis rangeAxis = new NumberAxis(); rangeAxis.setAutoRangeIncludesZero(false); rangeAxis.setTickLabelPaint(TsCharts.CHART_TICK_LABEL_COLOR); plot.setRangeAxis(rangeAxis); return result; }
From source file:fmiquerytest.Coordinates.java
static String drawTempRainChart(List<stepWeather> stepDataBase, Map routeWeather) { //First, fetch the real data List<Double> times = new ArrayList<>(); List<Double> temps = new ArrayList<>(); List<Double> rains = new ArrayList<>(); List<Double> lights = new ArrayList<>(); for (int i = 0; i < stepDataBase.size(); ++i) { stepWeather step = stepDataBase.get(i); stepWeather nextstep = step;/* w w w. jav a 2s .c om*/ if (i < stepDataBase.size() - 1) { nextstep = stepDataBase.get(i + 1); } times.add(step.timeAsDouble); temps.add(getParameterAverage(routeWeather, step, nextstep, "Temperature")); rains.add(getParameterAverage(routeWeather, step, nextstep, "Precipitation1h")); lights.add(Math.pow(Math.abs(step.timeAsDouble % 24 - ((step.sunRise + step.sunSet) / 2)) / ((step.sunSet - step.sunRise) / 2), 5)); } double zeroPoint = times.get(0); // Make first dataset final TimeSeriesCollection dataset = new TimeSeriesCollection(); final TimeSeries s1 = new TimeSeries("Temperature C", Minute.class); // Make second dataset final TimeSeriesCollection dataset2 = new TimeSeriesCollection(); final TimeSeries s2 = new TimeSeries("Rain (mm)", Minute.class); // Make third dataset //final TimeSeriesCollection dataset3 = new TimeSeriesCollection(); final TimeSeries s3 = new TimeSeries("Darkness", Minute.class); // Show data per minute RegularTimePeriod start = new Minute(new Date(FmiQueryTest.startTimeMillis)); for (int i = 0; i < times.size() - 1; ++i) { double time = times.get(i); double nexttime = times.get(i + 1); int firstMinute = intValue((time - zeroPoint) * 60); int currentMinute = firstMinute; int lastMinute = intValue((nexttime - zeroPoint) * 60); while (currentMinute < lastMinute) { s1.add(start, temps.get(i) + ((double) currentMinute - firstMinute) / (lastMinute - firstMinute) * (temps.get(i + 1) - temps.get(i))); s2.add(start, (rains.get(i) + rains.get(i + 1)) / 2); //+((double)currentMinute-firstMinute)/(lastMinute-firstMinute)*(rains.get(i+1)-rains.get(i))); s3.add(start, lights.get(i) + ((double) currentMinute - firstMinute) / (lastMinute - firstMinute) * (lights.get(i + 1) - lights.get(i))); ++currentMinute; start = start.next(); } } dataset.addSeries(s1); dataset2.addSeries(s3); dataset2.addSeries(s2); // Initialize chart final JFreeChart chart = ChartFactory.createTimeSeriesChart("Temperature and rain", "Time", "Temperature C", dataset, true, // legend? true, // tooltips? false // URLs? ); final XYPlot plot = chart.getXYPlot(); plot.getDomainAxis().setLowerMargin(0.0); plot.getDomainAxis().setUpperMargin(0.0); // configure the range axis to display first dataset... final ValueAxis rangeAxis = (ValueAxis) plot.getRangeAxis(); rangeAxis.setRange(-30, 30); final TickUnits units = new TickUnits(); units.add(new NumberTickUnit(10.0)); units.add(new NumberTickUnit(1.0)); units.add(new NumberTickUnit(0.1)); rangeAxis.setStandardTickUnits(units); //rangeAxis.setTickLabelFont(new Font("SansSerif", Font.BOLD, 16)); // add the secondary dataset/renderer/axis plot.setRangeAxis(rangeAxis); final XYItemRenderer renderer2 = new XYAreaRenderer(); final ValueAxis axis2 = new NumberAxis("Rain (mm) "); axis2.setRange(0, 2); axis2.setStandardTickUnits(units); //axis2.setTickLabelFont(new Font("SansSerif", Font.BOLD, 16)); renderer2.setSeriesPaint(0, new Color(0, 0, 255, 128)); plot.setDataset(1, dataset2); plot.setRenderer(1, renderer2); plot.setRangeAxis(1, axis2); plot.mapDatasetToRangeAxis(1, 1); final XYItemRenderer renderer3 = new XYAreaRenderer(); renderer3.setSeriesPaint(0, new Color(0, 0, 0, 64)); //plot.setDataset(1, dataset2); plot.setRenderer(1, renderer3); plot.setRangeAxis(1, axis2); plot.mapDatasetToRangeAxis(1, 1); chart.setBackgroundPaint(Color.white); //plot.setBackgroundPaint(Color.lightGray); plot.setBackgroundPaint(Color.white); plot.setDomainGridlinesVisible(true); plot.setDomainGridlinePaint(Color.black); plot.setRangeGridlinesVisible(true); plot.setRangeGridlinePaint(Color.black); // final TextTitle subtitle = new TextTitle("An area chart demonstration. We use this " // + "subtitle as an example of what happens when you get a really long title or " // + "subtitle."); // subtitle.setFont(new Font("SansSerif", Font.PLAIN, 12)); // subtitle.setPosition(RectangleEdge.TOP); //// subtitle.setSpacer(new Spacer(Spacer.RELATIVE, 0.05, 0.05, 0.05, 0.05)); // subtitle.setVerticalAlignment(VerticalAlignment.BOTTOM); // chart.addSubtitle(subtitle); // Produce chart // ChartFrame frame = new ChartFrame("Tamperature and rain", chart); // frame.pack(); // RefineryUtilities.centerFrameOnScreen(frame); // frame.setVisible(true); ByteArrayOutputStream bas = new ByteArrayOutputStream(); try { ChartUtilities.writeChartAsPNG(bas, chart, 600, 400); } catch (IOException ex) { Logger.getLogger(WeatherTools.class.getName()).log(Level.SEVERE, null, ex); } byte[] byteArray = bas.toByteArray(); String baseCode = Base64.encode(byteArray); return "<img width=\"480\" alt=\"Temperature and rain\" src=\"data:image/png;base64," + baseCode.trim() + "\" />"; }
From source file:com.stableapps.anglewraparounddemo.AngleWrapDemoMain.java
/** * Creates a sample chart.//from w w w . j av a 2 s.c om * * @return a sample chart. */ private JFreeChart createChart() { final XYDataset direction = createAngleDataset(600); final JFreeChart chart = ChartFactory.createTimeSeriesChart("Time", "Date", "Direction", direction, true, true, false); final XYPlot plot = chart.getXYPlot(); plot.getDomainAxis().setLowerMargin(0.0); plot.getDomainAxis().setUpperMargin(0.0); // configure the range axis to provide a fix set of TickUnits depending on size of chart NumberAxis rangeAxis = new NumberAxis() { /** * */ private static final long serialVersionUID = 1L; @Override public NumberTickUnit getTickUnit() { NumberTickUnit tickUnit = super.getTickUnit(); if (tickUnit.getSize() < 15) { return tickUnit; } else if (tickUnit.getSize() < 45) { return new NumberTickUnit(45); } else if (tickUnit.getSize() < 90) { return new NumberTickUnit(90); } else if (tickUnit.getSize() < 180) { return new NumberTickUnit(180); } else { return new NumberTickUnit(360); } } }; rangeAxis.setAutoRangeIncludesZero(false); plot.setRangeAxis(rangeAxis); final OverflowCondition overflowCondition = new OverflowCondition() { @Override public boolean isOverflow(double y0, double x0, double y1, double x1) { return Math.abs(y1 - y0) > 180; } }; XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false) { /** * */ private static final long serialVersionUID = 1L; double min = 0; double max = 360; LinearInterpolator interpolator = new LinearInterpolator(); @Override protected void drawPrimaryLine(XYItemRendererState state, Graphics2D g2, XYPlot plot, XYDataset dataset, int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) { if (item == 0) { return; } // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(y1) || Double.isNaN(x1)) { return; } double x0 = dataset.getXValue(series, item - 1); double y0 = dataset.getYValue(series, item - 1); if (Double.isNaN(y0) || Double.isNaN(x0)) { return; } if (overflowCondition.isOverflow(y0, x0, y1, x1)) { boolean overflowAtMax = y1 < y0; if (overflowAtMax) { LinearFunction lf = interpolator.interpolate(new double[] { y0, y1 + (max - min) }, new double[] { x0, x1 }); double xmid = lf.value(max); drawPrimaryLine(state, g2, plot, x0, y0, xmid, max, pass, series, item, domainAxis, rangeAxis, dataArea); drawPrimaryLine(state, g2, plot, xmid, min, x1, y1, pass, series, item, domainAxis, rangeAxis, dataArea); } else { LinearFunction lf = interpolator.interpolate(new double[] { y1 - (max - min), y0 }, new double[] { x1, x0 }); double xmid = lf.value(min); drawPrimaryLine(state, g2, plot, x0, y0, xmid, min, pass, series, item, domainAxis, rangeAxis, dataArea); drawPrimaryLine(state, g2, plot, xmid, max, x1, y1, pass, series, item, domainAxis, rangeAxis, dataArea); } } else { drawPrimaryLine(state, g2, plot, x0, y0, x1, y1, pass, series, item, domainAxis, rangeAxis, dataArea); } } private void drawPrimaryLine(XYItemRendererState state, Graphics2D g2, XYPlot plot, double x0, double y0, double x1, double y1, int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) { RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation); double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation); double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); // only draw if we have good values if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1) || Double.isNaN(transY1)) { return; } PlotOrientation orientation = plot.getOrientation(); boolean visible; if (orientation == PlotOrientation.HORIZONTAL) { state.workingLine.setLine(transY0, transX0, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { state.workingLine.setLine(transX0, transY0, transX1, transY1); } visible = LineUtilities.clipLine(state.workingLine, dataArea); if (visible) { drawFirstPassShape(g2, pass, series, item, state.workingLine); } } @Override protected void drawPrimaryLineAsPath(XYItemRendererState state, Graphics2D g2, XYPlot plot, XYDataset dataset, int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) { // get the data point... State s = (State) state; try { double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(x1) && Double.isNaN(y1)) { s.setLastPointGood(false); return; } if (!s.isLastPointGood()) { ImmutablePair<Float, Float> xy = translate(plot, domainAxis, rangeAxis, dataArea, x1, y1); s.seriesPath.moveTo(xy.getLeft(), xy.getRight()); s.setLastPointGood(true); return; } double x0 = dataset.getXValue(series, item - 1); double y0 = dataset.getYValue(series, item - 1); if (overflowCondition.isOverflow(y0, x0, y1, x1)) { boolean overflowAtMax = y1 < y0; if (overflowAtMax) { LinearFunction lf = interpolator.interpolate(new double[] { y0, y1 + (max - min) }, new double[] { x0, x1 }); double xmid = lf.value(max); ImmutablePair<Float, Float> xy = translate(plot, domainAxis, rangeAxis, dataArea, xmid, max); s.seriesPath.lineTo(xy.getLeft(), xy.getRight()); xy = translate(plot, domainAxis, rangeAxis, dataArea, xmid, min); s.seriesPath.moveTo(xy.getLeft(), xy.getRight()); xy = translate(plot, domainAxis, rangeAxis, dataArea, x1, y1); s.seriesPath.lineTo(xy.getLeft(), xy.getRight()); } else { LinearFunction lf = interpolator.interpolate(new double[] { y1 - (max - min), y0 }, new double[] { x1, x0 }); double xmid = lf.value(min); ImmutablePair<Float, Float> xy = translate(plot, domainAxis, rangeAxis, dataArea, xmid, min); s.seriesPath.lineTo(xy.getLeft(), xy.getRight()); xy = translate(plot, domainAxis, rangeAxis, dataArea, xmid, max); s.seriesPath.moveTo(xy.getLeft(), xy.getRight()); xy = translate(plot, domainAxis, rangeAxis, dataArea, x1, y1); s.seriesPath.lineTo(xy.getLeft(), xy.getRight()); } } else { ImmutablePair<Float, Float> xy = translate(plot, domainAxis, rangeAxis, dataArea, x1, y1); s.seriesPath.lineTo(xy.getLeft(), xy.getRight()); } s.setLastPointGood(true); } finally { // if this is the last item, draw the path ... if (item == s.getLastItemIndex()) { // draw path drawFirstPassShape(g2, pass, series, item, s.seriesPath); } } } private ImmutablePair<Float, Float> translate(XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea, double x, double y) { RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX1 = domainAxis.valueToJava2D(x, dataArea, xAxisLocation); double transY1 = rangeAxis.valueToJava2D(y, dataArea, yAxisLocation); // update path to reflect latest point float xtrans = (float) transX1; float ytrans = (float) transY1; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { xtrans = (float) transY1; ytrans = (float) transX1; } return new ImmutablePair<>(xtrans, ytrans); } }; renderer.setDrawSeriesLineAsPath(true); plot.setRenderer(0, renderer); return chart; }
From source file:org.codehaus.mojo.dashboard.report.plugin.chart.time.TimeChartRenderer.java
public void createChart() { XYDataset dataset = (XYDataset) this.datasetStrategy.getDataset(); report = ChartFactory.createTimeSeriesChart(this.datasetStrategy.getTitle(), // title this.datasetStrategy.getXAxisLabel(), // x-axis label this.datasetStrategy.getYAxisLabel(), // y-axis label dataset, // data true, // create legend? true, // generate tooltips? false // generate URLs? );/* www. ja va2 s . co m*/ // report.setBackgroundPaint( Color.lightGray ); XYPlot plot = report.getXYPlot(); plot.setBackgroundPaint(Color.white); plot.setDomainGridlinePaint(Color.lightGray); plot.setRangeGridlinePaint(Color.lightGray); plot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D)); XYItemRenderer xyitemrenderer = plot.getRenderer(); if (xyitemrenderer instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyitemrenderer; renderer.setBaseShapesVisible(true); renderer.setBaseShapesFilled(true); renderer.setBaseShapesVisible(true); renderer.setDrawOutlines(true); renderer.setBaseItemLabelGenerator( ((AbstractTimeChartStrategy) this.datasetStrategy).getLabelGenerator()); renderer.setBaseItemLabelFont(new Font("SansSerif", Font.BOLD, 10)); renderer.setBaseItemLabelsVisible(true); renderer.setBasePositiveItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE10, TextAnchor.BASELINE_RIGHT)); } Paint[] paints = this.datasetStrategy.getPaintColor(); for (int i = 0; i < dataset.getSeriesCount() && i < paints.length; i++) { xyitemrenderer.setSeriesPaint(i, paints[i]); xyitemrenderer.setSeriesStroke(i, new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); } plot.setRangeAxis(((AbstractTimeChartStrategy) this.datasetStrategy).getRangeAxis()); DashDateAxis axisDate = new DashDateAxis(); axisDate.setDateFormatOverride( ((AbstractTimeChartStrategy) this.datasetStrategy).getTimePeriod().getDateFormat()); axisDate.setLabel(this.datasetStrategy.getXAxisLabel()); axisDate.setTickUnit(getTickUnit(((AbstractTimeChartStrategy) this.datasetStrategy).getTimePeriod())); axisDate.setUpperMargin(0.0D); axisDate.setDateTickLabelAngle(-0.6); if (((AbstractTimeChartStrategy) this.datasetStrategy).getStartDate() != null && ((AbstractTimeChartStrategy) this.datasetStrategy).getEndDate() != null) { axisDate.setRangeWithMargins( new DateRange(((AbstractTimeChartStrategy) this.datasetStrategy).getStartDate(), ((AbstractTimeChartStrategy) this.datasetStrategy).getEndDate())); } plot.setDomainAxis(axisDate); Date[] dates = DateUtils.getAllDates(((AbstractTimeChartStrategy) this.datasetStrategy).getStartDate(), ((AbstractTimeChartStrategy) this.datasetStrategy).getEndDate(), ((AbstractTimeChartStrategy) this.datasetStrategy).getTimePeriod()); int width = (dates.length * ChartUtils.STANDARD_TIME_ENTRY_WIDTH) + ChartUtils.STANDARD_TIME_ADDITIONAL_WIDTH; if (width > ChartUtils.MINIMUM_WIDTH) { this.setWidth(width); } else { this.setWidth(ChartUtils.MINIMUM_WIDTH); } }