List of usage examples for org.jfree.chart.plot XYPlot setDomainGridlinesVisible
public void setDomainGridlinesVisible(boolean visible)
From source file:com.jtstand.swing.StatsPanel.java
public JFreeChart getChartTime() { TreeMap<String, List<TestStepInstance>> s = getGroupedSteps(getFilteringIterator()); if (s == null || s.size() == 0) { return null; }// w ww . ja va 2s. com TimeSeriesCollection dataset = new TimeSeriesCollection(); for (Iterator<String> en = s.keySet().iterator(); en.hasNext();) { String groupName = en.next(); List<TestStepInstance> stps = s.get(groupName); // TimeSeries pop = new TimeSeries(groupName, Millisecond.class); TimeSeries pop = new TimeSeries(groupName); for (Iterator<TestStepInstance> it = stps.iterator(); it.hasNext();) { TestStepInstance step = it.next(); Number num = getNumber(step); if (num != null) { switch (chartMode) { case STEP_TIME: pop.addOrUpdate(RegularTimePeriod.createInstance(Millisecond.class, new Date(step.getStartTime()), TimeZone.getDefault()), num); break; case SEQUENCE_TIME: // pop.addOrUpdate(RegularTimePeriod.createInstance(Millisecond.class, new Date(step.getTestSequenceInstance().getStartTime()), RegularTimePeriod.DEFAULT_TIME_ZONE), num); pop.addOrUpdate(RegularTimePeriod.createInstance(Millisecond.class, new Date(step.getTestSequenceInstance().getCreateTime()), TimeZone.getDefault()), num); break; } } } dataset.addSeries(pop); } JFreeChart chart = null; switch (chartMode) { case STEP_TIME: chart = ChartFactory.createTimeSeriesChart(null, "Step Started Time", getValueString(), dataset, isGrouping(), true, false); break; case SEQUENCE_TIME: chart = ChartFactory.createTimeSeriesChart(null, "Sequence Started Time", getValueString(), dataset, isGrouping(), true, false); break; } chart.setBackgroundPaint((Paint) UIManager.get("Panel.background")); XYPlot plot = chart.getXYPlot(); plot.setBackgroundPaint(Color.white); XYLineAndShapeRenderer renderer5 = new XYLineAndShapeRenderer(); renderer5.setBaseSeriesVisibleInLegend(false); plot.setRenderer(renderer5); plot.setDomainGridlinesVisible(true); plot.setRangeGridlinesVisible(true); plot.setRangeCrosshairVisible(true); plot.setDomainCrosshairVisible(true); // chart.setTitle(valueName); placeLimitMarkers(plot, true); //renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); renderer5.setBaseToolTipGenerator(StandardXYToolTipGenerator.getTimeSeriesInstance()); /* coloring */ if (isCategorization()) { // TreeMap<String, Color> cmap = new TreeMap<String, Color>(); int i = 0; for (Iterator<String> it = catstats.keySet().iterator(); it.hasNext(); i++) { String groupName = it.next(); Color c = ChartCategories.getColor(i); for (int j = 0; j < dataset.getSeriesCount(); j++) { TimeSeries ts = dataset.getSeries(j); if (ts.getKey().equals(groupName)) { renderer5.setSeriesPaint(j, c); } } } } else { renderer5.setSeriesPaint(0, ChartCategories.getColor(0)); } // chart.addProgressListener(new ChartProgressListener() { // // public void chartProgress(final ChartProgressEvent progress) { // SwingUtilities.invokeLater( // new Runnable() { // // @Override // public void run() { // // System.out.println("progress:" + progress + " " + progress.getType()); // if (progress.getType() == ChartProgressEvent.DRAWING_FINISHED) { // if (plot != null) { // if (plot.isDomainCrosshairVisible() && plot.isDomainCrosshairLockedOnData()) { //// System.out.println("getDomainCrosshairValue:" + plot.getDomainCrosshairValue()); // double xx = plot.getDomainCrosshairValue(); // if (xx != 0.0) { // long x = (long) xx; // System.out.println(new Date(x)); // for (TestStepInstance step : testStepInstances.getSteps()) { // if (step.getStartTime() != null && step.getStartTime().equals(x)) { // testStepInstances.selectStep(step); // } // } // System.out.println(new Date(x)); // } // } //// if (plot.isRangeCrosshairVisible()) { //// System.out.println("getRangeCrosshairValue:" + plot.getRangeCrosshairValue()); //// } // } // } // } // }); // } // }); // chart.addChangeListener(new ChartChangeListener() { // // public void chartChanged(ChartChangeEvent event) { // System.out.println("event:" + event); // if (event != null) { //// JFreeChart chart = event.getChart(); //// System.out.println("chart:" + chart); //// if (chart != null) { //// System.out.println("title:" + event.getChart().getTitle()); //// } // System.out.println("type:" + event.getType()); // if (plot != null) { // if (plot.isDomainCrosshairVisible()) { // System.out.println("getDomainCrosshairValue:" + plot.getDomainCrosshairValue()); // long x = (long) plot.getDomainCrosshairValue(); // for (TestStepInstance step : testStepInstances.getSteps()) { // if (step.getStartTime() != null && step.getStartTime().equals(x)) { // testStepInstances.selectStep(step); // } // } // System.out.println(new Date(x)); // } // if (plot.isRangeCrosshairVisible()) { // System.out.println("getRangeCrosshairValue:" + plot.getRangeCrosshairValue()); // } // } // } // } // }); chart.setTextAntiAlias(false); return chart; }
From source file:edu.fullerton.viewerplugin.SpectrumPlot.java
private ChartPanel getPanel(ArrayList<ChanDataBuffer> dbufs, boolean compact) throws WebUtilException { ChartPanel ret = null;//from w ww .jav a 2 s . 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:ro.nextreports.engine.chart.JFreeChartExporter.java
private JFreeChart createLineChart() throws QueryException { XYSeriesCollection dataset = new XYSeriesCollection(); String chartTitle = replaceParameters(chart.getTitle().getTitle()); chartTitle = StringUtil.getI18nString(chartTitle, I18nUtil.getLanguageByName(chart, language)); Object[] charts = new Object[chart.getYColumns().size()]; List<String> legends = chart.getYColumnsLegends(); boolean hasLegend = false; for (int i = 0; i < charts.length; i++) { String legend = ""; try {//w ww . j a v a2s. c om legend = replaceParameters(legends.get(i)); legend = StringUtil.getI18nString(legend, I18nUtil.getLanguageByName(chart, language)); } catch (IndexOutOfBoundsException ex) { // no legend set } if ((legend != null) && !"".equals(legend.trim())) { hasLegend = true; } XYSeries lineChart = new XYSeries(legend); charts[i] = lineChart; dataset.addSeries(lineChart); } String xLegend = StringUtil.getI18nString(replaceParameters(chart.getXLegend().getTitle()), I18nUtil.getLanguageByName(chart, language)); String yLegend = StringUtil.getI18nString(replaceParameters(chart.getYLegend().getTitle()), I18nUtil.getLanguageByName(chart, language)); JFreeChart jfreechart = ChartFactory.createXYLineChart(chartTitle, // Title replaceParameters(xLegend), // x-axis Label replaceParameters(yLegend), // y-axis Label dataset, // Dataset PlotOrientation.VERTICAL, // Plot Orientation true, // Show Legend true, // Use tooltips false // Configure chart to generate URLs? ); // hide legend if necessary if (!hasLegend) { jfreechart.removeLegend(); } // hide border jfreechart.setBorderVisible(false); // title setTitle(jfreechart); // charts colors & values boolean showValues = (chart.getShowYValuesOnChart() == null) ? false : chart.getShowYValuesOnChart(); DecimalFormat decimalFormat; DecimalFormat percentageFormat; if (chart.getYTooltipPattern() == null) { decimalFormat = new DecimalFormat("#"); percentageFormat = new DecimalFormat("0.00%"); } else { decimalFormat = new DecimalFormat(chart.getYTooltipPattern()); percentageFormat = decimalFormat; } XYPlot plot = (XYPlot) jfreechart.getPlot(); for (int i = 0; i < charts.length; i++) { plot.getRenderer().setSeriesPaint(i, chart.getForegrounds().get(i)); if (showValues) { plot.getRenderer().setSeriesItemLabelsVisible(i, true); plot.getRenderer().setSeriesItemLabelGenerator(i, new StandardXYItemLabelGenerator("{2}", decimalFormat, percentageFormat)); } } if (showValues) { // increase a little bit the range axis to view all item label values over points plot.getRangeAxis().setUpperMargin(0.2); } // grid axis visibility & colors if ((chart.getXShowGrid() != null) && !chart.getXShowGrid()) { plot.setDomainGridlinesVisible(false); } else { if (chart.getXGridColor() != null) { plot.setDomainGridlinePaint(chart.getXGridColor()); } else { plot.setDomainGridlinePaint(Color.BLACK); } } if ((chart.getYShowGrid() != null) && !chart.getYShowGrid()) { plot.setRangeGridlinesVisible(false); } else { if (chart.getYGridColor() != null) { plot.setRangeGridlinePaint(chart.getYGridColor()); } else { plot.setRangeGridlinePaint(Color.BLACK); } } // chart background plot.setBackgroundPaint(chart.getBackground()); // labels color plot.getDomainAxis().setTickLabelPaint(chart.getXColor()); plot.getRangeAxis().setTickLabelPaint(chart.getYColor()); //legend color plot.getDomainAxis().setLabelPaint(chart.getXLegend().getColor()); plot.getRangeAxis().setLabelPaint(chart.getYLegend().getColor()); // legend font plot.getDomainAxis().setLabelFont(chart.getXLegend().getFont()); plot.getRangeAxis().setLabelFont(chart.getYLegend().getFont()); // hide labels if ((chart.getXShowLabel() != null) && !chart.getXShowLabel()) { plot.getDomainAxis().setTickLabelsVisible(false); plot.getDomainAxis().setTickMarksVisible(false); } if ((chart.getYShowLabel() != null) && !chart.getYShowLabel()) { plot.getRangeAxis().setTickLabelsVisible(false); plot.getRangeAxis().setTickMarksVisible(false); } // label orientation if (chart.getXorientation() == Chart.VERTICAL) { plot.getDomainAxis().setVerticalTickLabels(true); } // labels fonts plot.getDomainAxis().setTickLabelFont(chart.getXLabelFont()); plot.getRangeAxis().setTickLabelFont(chart.getYLabelFont()); // point style Shape pointShape = null; byte style = chart.getType().getStyle(); switch (style) { case ChartType.STYLE_LINE_DOT_SOLID: case ChartType.STYLE_LINE_DOT_HOLLOW: pointShape = new Ellipse2D.Float(-3.0f, -3.0f, 6.0f, 6.0f); break; case ChartType.STYLE_LINE_DOT_ANCHOR: // triangle GeneralPath s5 = new GeneralPath(); s5.moveTo(0.0f, -3.0f); s5.lineTo(3.0f, 3.0f); s5.lineTo(-3.0f, 3.0f); s5.closePath(); pointShape = s5; break; case ChartType.STYLE_LINE_DOT_BOW: GeneralPath s4 = new GeneralPath(); s4.moveTo(-3.0f, -3.0f); s4.lineTo(3.0f, -3.0f); s4.lineTo(-3.0f, 3.0f); s4.lineTo(3.0f, 3.0f); s4.closePath(); pointShape = s4; break; case ChartType.STYLE_LINE_DOT_STAR: pointShape = new Star(-3.0f, 0f).getShape(); break; default: // no shape break; } if (pointShape != null) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); renderer.setUseFillPaint(true); for (int i = 0; i < charts.length; i++) { renderer.setSeriesShapesVisible(i, true); if (style != ChartType.STYLE_LINE_DOT_SOLID) { renderer.setSeriesFillPaint(i, chart.getBackground()); } else { renderer.setSeriesFillPaint(i, chart.getForegrounds().get(i)); } renderer.setSeriesShape(i, pointShape); } } final HashMap<String, String> formatValues = createChart(plot.getRangeAxis(), charts); // in x axis does not contain number values , values are strings representing one unit if (!integerXValue) { ((NumberAxis) plot.getDomainAxis()).setTickUnit(new NumberTickUnit(1)); ((NumberAxis) plot.getDomainAxis()).setNumberFormatOverride(new DecimalFormat() { @Override public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition) { String s = formatValues.get(String.valueOf(Math.round(number))); if (s == null) { s = ""; } return result.append(s); } }); } return jfreechart; }
From source file:ro.nextreports.engine.chart.JFreeChartExporter.java
private JFreeChart createBubbleChart() throws QueryException { bubbleDataset = new DefaultXYZDataset(); // x, y are inverted for jfree bubble chart! // that's why we use minX & maxX values to compute Tu (tickUnit) String chartTitle = replaceParameters(chart.getTitle().getTitle()); chartTitle = StringUtil.getI18nString(chartTitle, I18nUtil.getLanguageByName(chart, language)); String xLegend = StringUtil.getI18nString(replaceParameters(chart.getYLegend().getTitle()), I18nUtil.getLanguageByName(chart, language)); String yLegend = StringUtil.getI18nString(replaceParameters(chart.getXLegend().getTitle()), I18nUtil.getLanguageByName(chart, language)); JFreeChart jfreechart = ChartFactory.createBubbleChart(chartTitle, xLegend, // x-axis Label yLegend, // y-axis Label bubbleDataset, PlotOrientation.HORIZONTAL, true, true, false); // hide border jfreechart.setBorderVisible(false);// w ww . j a v a 2 s .co m // title setTitle(jfreechart); boolean showValues = (chart.getShowYValuesOnChart() == null) ? false : chart.getShowYValuesOnChart(); XYPlot xyplot = (XYPlot) jfreechart.getPlot(); xyplot.setForegroundAlpha(transparency); XYItemRenderer xyitemrenderer = xyplot.getRenderer(); DecimalFormat decimalformat; DecimalFormat percentageFormat; if (chart.getYTooltipPattern() == null) { decimalformat = new DecimalFormat("#"); percentageFormat = new DecimalFormat("0.00%"); } else { decimalformat = new DecimalFormat(chart.getYTooltipPattern()); percentageFormat = decimalformat; } if (showValues) { // increase a little bit the range axis to view all item label values over bars xyplot.getRangeAxis().setUpperMargin(0.2); } // grid axis visibility & colors if ((chart.getXShowGrid() != null) && !chart.getXShowGrid()) { xyplot.setDomainGridlinesVisible(false); } else { if (chart.getXGridColor() != null) { xyplot.setDomainGridlinePaint(chart.getXGridColor()); } else { xyplot.setDomainGridlinePaint(Color.BLACK); } } if ((chart.getYShowGrid() != null) && !chart.getYShowGrid()) { xyplot.setRangeGridlinesVisible(false); } else { if (chart.getYGridColor() != null) { xyplot.setRangeGridlinePaint(chart.getYGridColor()); } else { xyplot.setRangeGridlinePaint(Color.BLACK); } } // chart background xyplot.setBackgroundPaint(chart.getBackground()); // labels color xyplot.getDomainAxis().setTickLabelPaint(chart.getXColor()); xyplot.getRangeAxis().setTickLabelPaint(chart.getYColor()); // legend color xyplot.getDomainAxis().setLabelPaint(chart.getXLegend().getColor()); xyplot.getRangeAxis().setLabelPaint(chart.getYLegend().getColor()); // legend font xyplot.getDomainAxis().setLabelFont(chart.getXLegend().getFont()); xyplot.getRangeAxis().setLabelFont(chart.getYLegend().getFont()); // axis color xyplot.getDomainAxis().setAxisLinePaint(chart.getxAxisColor()); xyplot.getRangeAxis().setAxisLinePaint(chart.getyAxisColor()); // hide labels if ((chart.getXShowLabel() != null) && !chart.getXShowLabel()) { xyplot.getDomainAxis().setTickLabelsVisible(false); xyplot.getDomainAxis().setTickMarksVisible(false); } if ((chart.getYShowLabel() != null) && !chart.getYShowLabel()) { xyplot.getRangeAxis().setTickLabelsVisible(false); xyplot.getRangeAxis().setTickMarksVisible(false); } // label orientation ValueAxis domainAxis = xyplot.getDomainAxis(); if (chart.getXorientation() == Chart.VERTICAL) { domainAxis.setLabelAngle(Math.PI / 2); } else if (chart.getXorientation() == Chart.DIAGONAL) { domainAxis.setLabelAngle(Math.PI / 4); } else if (chart.getXorientation() == Chart.HALF_DIAGONAL) { domainAxis.setLabelAngle(Math.PI / 8); } // labels fonts xyplot.getDomainAxis().setTickLabelFont(chart.getXLabelFont()); xyplot.getRangeAxis().setTickLabelFont(chart.getYLabelFont()); createChart(xyplot.getRangeAxis(), new Object[4]); double minX = Double.MAX_VALUE; double maxX = Double.MIN_VALUE; double minY = Double.MAX_VALUE; double maxY = Double.MIN_VALUE; double maxZ = Double.MIN_VALUE; for (String serie : bubbleData.keySet()) { XYZList xyzList = bubbleData.get(serie); List<Number> yList = xyzList.getyList(); for (Number n : yList) { minY = Math.min(minY, n.doubleValue()); maxY = Math.max(maxY, n.doubleValue()); } List<Number> xList = xyzList.getxList(); for (Number n : xList) { minX = Math.min(minX, n.doubleValue()); maxX = Math.max(maxX, n.doubleValue()); } List<Number> zList = xyzList.getzList(); for (Number n : zList) { maxZ = Math.max(maxZ, n.doubleValue()); } } double tu = Math.floor((maxX - minX) / 5 + 0.5d); NumberTickUnit rUnit = new NumberTickUnit(tu); ((NumberAxis) xyplot.getRangeAxis()).setTickUnit(rUnit); // make the bubble with text fit on X axis (which is shown vertically!) xyplot.getDomainAxis().setUpperMargin(0.2); xyplot.getDomainAxis().setLowerMargin(0.2); for (String serie : bubbleData.keySet()) { XYZList xyzList = bubbleData.get(serie); double[][] data = { getDoubleArray(xyzList.getyList()), getDoubleArray(xyzList.getxList()), getZDoubleArray(xyzList.getzList(), tu, maxZ) }; bubbleDataset.addSeries(serie, data); } int series = bubbleData.keySet().size(); for (int i = 0; i < series; i++) { xyitemrenderer.setSeriesPaint(i, chart.getForegrounds().get(i)); if (showValues) { xyitemrenderer.setSeriesItemLabelsVisible(i, true); xyitemrenderer.setSeriesItemLabelGenerator(i, new StandardXYItemLabelGenerator("{2}", decimalformat, percentageFormat)); } } // show labels on bubbles xyitemrenderer.setBaseItemLabelsVisible(true); xyitemrenderer.setBaseItemLabelGenerator(new LegendXYItemLabelGenerator()); return jfreechart; }
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 . ja v a2 s. c o m*/ 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:skoa.helpers.Graficos.java
private void evolucionDual() { TimeSeries serie;/*from www. ja v a2 s. c om*/ XYDataset dataset = null; ui = 0; nombreFichero = nombresFicheros.elementAt(0); unidad = buscarUnidad(nombreFichero); serie = obtenerSerieEvolucion(); dataset = new TimeSeriesCollection(serie); //Para generar el grfico se usa createTimeSeriesChart para ver la evolucin de las fechas. JFreeChart grafica = ChartFactory.createTimeSeriesChart("Valores medidos de las direcciones de grupo", //titulo "Fechas", //titulo eje x "Mediciones (" + unidad + ")", //titulo eje y dataset, //dataset true, //leyenda true, //tooltips false); //configure chart to generate URLs? //Dar color a cada categoria grafica.setBackgroundPaint(Color.WHITE); //Color del fondo del grfico //CREACIN DEL SEGUNDO EJE CON SU CORRESPONDIENTE DATASET. XYDataset dataset2 = null; ui = 0; nombreFichero = nombresFicheros.elementAt(1); unidad = buscarUnidad(nombreFichero); final XYPlot plot = grafica.getXYPlot(); final NumberAxis axis2 = new NumberAxis("Mediciones (" + unidad + ")"); axis2.setAutoRangeIncludesZero(false); plot.setRangeAxis(1, axis2); serie = obtenerSerieEvolucion(); dataset2 = new TimeSeriesCollection(serie); plot.setDataset(1, dataset2); plot.mapDatasetToRangeAxis(1, 1); final StandardXYItemRenderer renderer2 = new StandardXYItemRenderer(); renderer2.setSeriesPaint(0, Color.blue); plot.setRenderer(1, renderer2); plot.setBackgroundPaint(new Color(0xEE, 0xEE, 0xFF));//igual color de fondo que el de barrasDual plot.setDomainGridlinesVisible(true); //Ver lineas divisorias. plot.setRangeGridlinePaint(Color.BLACK);//Color de las lineas divisorias. //--------------------------------------------------------------------- if (fechaInicial.equals("") & fechaFinal.equals("")) { //Si estn vacas es porque no hay resultados para ese intervalo. fechaInicial = " ? "; fechaFinal = " ? "; } TextTitle t = new TextTitle("desde " + fechaInicial + " hasta " + fechaFinal, new Font("SanSerif", Font.ITALIC, 12)); grafica.addSubtitle(t); try { ChartUtilities.saveChartAsJPEG(new File(ruta + "EvolucionSmall.jpg"), grafica, 400, 300); ChartUtilities.saveChartAsJPEG(new File(ruta + "EvolucionBig.jpg"), grafica, 900, 600); } catch (IOException e1) { System.err.println("Problem occurred creating chart." + e1); } }
From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentQCController.java
private boolean writeDetailedFactorAnalysis(ExpressionExperiment ee, OutputStream os) throws Exception { SVDValueObject svdo = svdService.getSvdFactorAnalysis(ee.getId()); if (svdo == null) return false; if (svdo.getFactors().isEmpty() && svdo.getDates().isEmpty()) { return false; }/*from ww w. j a v a 2 s. com*/ Map<Integer, Map<Long, Double>> factorCorrelations = svdo.getFactorCorrelations(); // Map<Integer, Map<Long, Double>> factorPvalues = svdo.getFactorPvalues(); Map<Integer, Double> dateCorrelations = svdo.getDateCorrelations(); assert ee.getId().equals(svdo.getId()); ee = expressionExperimentService.thawLite(ee); // need the experimental design int maxWidth = 30; Map<Long, String> efs = this.getFactorNames(ee, maxWidth); Map<Long, ExperimentalFactor> efIdMap = EntityUtils .getIdMap(ee.getExperimentalDesign().getExperimentalFactors()); Collection<Long> continuousFactors = new HashSet<>(); for (ExperimentalFactor ef : ee.getExperimentalDesign().getExperimentalFactors()) { boolean isContinous = ExperimentalDesignUtils.isContinuous(ef); if (isContinous) { continuousFactors.add(ef.getId()); } } /* * Make plots of the dates vs. PCs, factors vs. PCs. */ int MAX_COMP = 3; Map<Long, List<JFreeChart>> charts = new LinkedHashMap<>(); ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme()); /* * FACTORS */ String componentShorthand = "PC"; for (Integer component : factorCorrelations.keySet()) { if (component >= MAX_COMP) break; String xaxisLabel = componentShorthand + (component + 1); for (Long efId : factorCorrelations.get(component).keySet()) { /* * Should not happen. */ if (!efs.containsKey(efId)) { log.warn("No experimental factor with id " + efId); continue; } if (!svdo.getFactors().containsKey(efId)) { // this should not happen. continue; } boolean isCategorical = !continuousFactors.contains(efId); Map<Long, String> categories = new HashMap<>(); if (isCategorical) { this.getCategories(efIdMap, efId, categories); } if (!charts.containsKey(efId)) { charts.put(efId, new ArrayList<JFreeChart>()); } Double a = factorCorrelations.get(component).get(efId); String plotname = (efs.get(efId) == null ? "?" : efs.get(efId)) + " " + xaxisLabel; // unique? if (a != null && !Double.isNaN(a)) { String title = plotname + " " + String.format("%.2f", a); List<Double> values = svdo.getFactors().get(efId); Double[] eigenGene = this.getEigenGene(svdo, component); assert values.size() == eigenGene.length; /* * Plot eigengene vs values, add correlation to the plot */ JFreeChart chart; if (isCategorical) { /* * Categorical factor */ // use the absolute value of the correlation, since direction is arbitrary. title = plotname + " " + String.format("r=%.2f", Math.abs(a)); DefaultMultiValueCategoryDataset dataset = new DefaultMultiValueCategoryDataset(); /* * What this code does is organize the factor values by the groups. */ Map<String, List<Double>> groupedValues = new TreeMap<>(); for (int i = 0; i < values.size(); i++) { Long fvId = values.get(i).longValue(); String fvValue = categories.get(fvId); if (fvValue == null) { /* * Problem ...eg gill2006fateinocean id=1748 -- missing values. We just don't plot * anything for this sample. */ continue; // is this all we need to do? } if (!groupedValues.containsKey(fvValue)) { groupedValues.put(fvValue, new ArrayList<Double>()); } groupedValues.get(fvValue).add(eigenGene[i]); if (log.isDebugEnabled()) log.debug(fvValue + " " + values.get(i)); } for (String key : groupedValues.keySet()) { dataset.add(groupedValues.get(key), plotname, key); } // don't show the name of the X axis: it's redundant with the title. NumberAxis rangeAxis = new NumberAxis(xaxisLabel); rangeAxis.setAutoRangeIncludesZero(false); // rangeAxis.setAutoRange( false ); rangeAxis.setAutoRangeMinimumSize(4.0); // rangeAxis.setRange( new Range( -2, 2 ) ); CategoryPlot plot = new CategoryPlot(dataset, new CategoryAxis(null), rangeAxis, new ScatterRenderer()); plot.setRangeGridlinesVisible(false); plot.setDomainGridlinesVisible(false); chart = new JFreeChart(title, new Font("SansSerif", Font.BOLD, 12), plot, false); ScatterRenderer renderer = (ScatterRenderer) plot.getRenderer(); float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP); renderer.setSeriesFillPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f)); renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3)); renderer.setUseOutlinePaint(false); renderer.setUseFillPaint(true); renderer.setBaseFillPaint(Color.white); CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); } else { /* * Continuous value factor */ DefaultXYDataset series = new DefaultXYDataset(); series.addSeries(plotname, new double[][] { ArrayUtils.toPrimitive(values.toArray(new Double[] {})), ArrayUtils.toPrimitive(eigenGene) }); // don't show x-axis label, which would otherwise be efs.get( efId ) chart = ChartFactory.createScatterPlot(title, null, xaxisLabel, series, PlotOrientation.VERTICAL, false, false, false); XYPlot plot = chart.getXYPlot(); plot.setRangeGridlinesVisible(false); plot.setDomainGridlinesVisible(false); XYItemRenderer renderer = plot.getRenderer(); renderer.setBasePaint(Color.white); renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3)); float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP); renderer.setSeriesPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f)); plot.setRenderer(renderer); } chart.getTitle().setFont(new Font("SansSerif", Font.BOLD, 12)); charts.get(efId).add(chart); } } } /* * DATES */ charts.put(-1L, new ArrayList<JFreeChart>()); for (Integer component : dateCorrelations.keySet()) { String xaxisLabel = componentShorthand + (component + 1); List<Date> dates = svdo.getDates(); if (dates.isEmpty()) break; long secspan = ubic.basecode.util.DateUtil.numberOfSecondsBetweenDates(dates); if (component >= MAX_COMP) break; Double a = dateCorrelations.get(component); if (a != null && !Double.isNaN(a)) { Double[] eigenGene = svdo.getvMatrix().getColObj(component); /* * Plot eigengene vs values, add correlation to the plot */ TimeSeries series = new TimeSeries("Dates vs. eigen" + (component + 1)); int i = 0; for (Date d : dates) { // if span is less than an hour, retain the minute. if (secspan < 60 * 60) { series.addOrUpdate(new Minute(d), eigenGene[i++]); } else { series.addOrUpdate(new Hour(d), eigenGene[i++]); } } TimeSeriesCollection dataset = new TimeSeriesCollection(); dataset.addSeries(series); JFreeChart chart = ChartFactory.createTimeSeriesChart( "Dates: " + xaxisLabel + " " + String.format("r=%.2f", a), null, xaxisLabel, dataset, false, false, false); XYPlot xyPlot = chart.getXYPlot(); chart.getTitle().setFont(new Font("SansSerif", Font.BOLD, 12)); // standard renderer makes lines. XYDotRenderer renderer = new XYDotRenderer(); renderer.setBaseFillPaint(Color.white); renderer.setDotHeight(3); renderer.setDotWidth(3); renderer.setSeriesShape(0, new Ellipse2D.Double(0, 0, 3, 3)); // has no effect, need dotheight. float saturationDrop = (float) Math.min(1.0, component * 0.8f / MAX_COMP); renderer.setSeriesPaint(0, Color.getHSBColor(0.0f, 1.0f - saturationDrop, 0.7f)); ValueAxis domainAxis = xyPlot.getDomainAxis(); domainAxis.setVerticalTickLabels(true); xyPlot.setRenderer(renderer); xyPlot.setRangeGridlinesVisible(false); xyPlot.setDomainGridlinesVisible(false); charts.get(-1L).add(chart); } } /* * Plot in a grid, with each factor as a column. FIXME What if we have too many factors to fit on the screen? */ int columns = (int) Math.ceil(charts.size()); int perChartSize = ExpressionExperimentQCController.DEFAULT_QC_IMAGE_SIZE_PX; BufferedImage image = new BufferedImage(columns * perChartSize, MAX_COMP * perChartSize, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = image.createGraphics(); int currentX = 0; int currentY = 0; for (Long id : charts.keySet()) { for (JFreeChart chart : charts.get(id)) { this.addChartToGraphics(chart, g2, currentX, currentY, perChartSize, perChartSize); if (currentY + perChartSize < MAX_COMP * perChartSize) { currentY += perChartSize; } else { currentY = 0; currentX += perChartSize; } } } os.write(ChartUtilities.encodeAsPNG(image)); return true; }
From source file:graficoyoutube.Grafico.java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: ChartPanel panel;//from w w w . ja v a 2s . co m JFreeChart chart = null; if (l.isSelected()) { //Graficas de Lineas int validar = 1; XYSplineRenderer renderer = new XYSplineRenderer(); XYSeriesCollection dataset = new XYSeriesCollection(); ValueAxis x = new NumberAxis(); ValueAxis y = new NumberAxis(); XYSeries serie = new XYSeries("Datos"); XYPlot plot; lineas.removeAll(); try { for (int fila = 0; fila <= datos.getRowCount(); fila++) { serie.add(Float.parseFloat(String.valueOf(datos.getValueAt(fila, 0))), Float.parseFloat(String.valueOf(datos.getValueAt(fila, 1)))); //JOptionPane.showMessageDialog(this,datos.getValueAt(fila, 0)+" ,"+ datos.getValueAt(fila, 1)); } } catch (Exception ex) { validar = 0; JOptionPane.showMessageDialog(this, ex.getMessage() + "\n" + validar); } if (validar == 1) { dataset.addSeries(serie); x.setLabel("Eje X"); y.setLabel("Eje Y"); plot = new XYPlot(dataset, x, y, renderer); chart = new JFreeChart(plot); chart.setTitle("Grafico de Lineas YouTube"); } else { JOptionPane.showMessageDialog(this, "Debe llenar la tabla con datos numericos"); } } else { if (b.isSelected()) { //Grafico de Barras DefaultCategoryDataset data = new DefaultCategoryDataset(); String producto1 = "Sopas"; String producto2 = "Soda"; String dia1 = "Dia 1"; String dia2 = "Dia 2"; String dia3 = "Dia 3"; String dia4 = "Dia 4"; data.addValue(18, producto1, dia1); data.addValue(15, producto1, dia2); data.addValue(14, producto1, dia3); data.addValue(1, producto1, dia4); data.addValue(50, producto2, dia1); data.addValue(45, producto2, dia2); data.addValue(31, producto2, dia3); data.addValue(10, producto2, dia4); chart = ChartFactory.createBarChart("Grafico de Barras YouTube", "Dia", "Cantidad", data, PlotOrientation.HORIZONTAL, true, true, true); CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.setDomainGridlinesVisible(true); } else { //Grafico de Pastel DefaultPieDataset data = new DefaultKeyedValuesDataset(); data.setValue("Categoria 1", 20); data.setValue("Categoria 2", 60); data.setValue("Categoria 3", 20); chart = ChartFactory.createPieChart3D("Grafico de Pastel", data, true, true, true); } } panel = new ChartPanel(chart); panel.setBounds(5, 10, 410, 400); if (l.isSelected()) { //Lineas lineas.add(panel); lineas.repaint(); } else { if (b.isSelected()) { barras.add(panel); barras.repaint(); } else { pastel.add(panel); pastel.repaint(); } } }
From source file:whitebox.stats.Kriging.java
/** * Draw Semivariogram surface map and also draw the search are if * Anisotropic/*from ww w. ja va2 s. c o m*/ * * @param Radius * @param AnIsotropic */ public void DrawSemivariogramSurface(double Radius, boolean AnIsotropic) { double[][] data = new double[3][BinSurface.length * BinSurface[0].length]; int n = 0; double max = Double.MIN_VALUE; for (int i = 0; i < BinSurface.length; i++) { for (int j = 0; j < BinSurface[i].length; j++) { data[0][n] = BinSurface[i][j].GridHorDistance; data[1][n] = BinSurface[i][j].GridVerDistance; if ((Math.pow(data[0][n], 2) + Math.pow(data[1][n], 2)) <= Radius * Radius && !Double.isNaN(BinSurface[i][j].Value)) { data[2][n] = BinSurface[i][j].Value; if (max < data[2][n]) { max = data[2][n]; } } else { data[2][n] = -1; } n++; } } DefaultXYZDataset dataset = new DefaultXYZDataset(); dataset.addSeries("Value", data); NumberAxis xAxis = new NumberAxis(); xAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); xAxis.setLowerMargin(0.0); xAxis.setUpperMargin(0.0); NumberAxis yAxis = new NumberAxis(); yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); yAxis.setLowerMargin(0.0); yAxis.setUpperMargin(0.0); XYBlockRenderer renderer = new XYBlockRenderer(); renderer.setBlockWidth(LagSize); renderer.setBlockHeight(LagSize); renderer.setBlockAnchor(RectangleAnchor.CENTER); LookupPaintScale paintScale = new LookupPaintScale(0, max, Color.white); double colorRange = max / 6; //double colorRange = 23013; paintScale.add(0.0, Color.blue); paintScale.add(1 * colorRange, Color.green); paintScale.add(2 * colorRange, Color.cyan); paintScale.add(3 * colorRange, Color.yellow); paintScale.add(4 * colorRange, Color.ORANGE); paintScale.add(5 * colorRange, Color.red); renderer.setPaintScale(paintScale); XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinesVisible(false); plot.setRangeGridlinePaint(Color.white); if (AnIsotropic) { CombinedRangeXYPlot combinedrangexyplot = new CombinedRangeXYPlot(); XYSeries seriesT1 = new XYSeries("1"); XYSeriesCollection AngleCollct = new XYSeriesCollection(); double bw = BandWidth; double r = bw / Math.sin(Tolerance); if (r > Radius) { bw = Radius * Math.sin(Tolerance); r = Radius; } seriesT1.add(r * Math.cos(Angle + Tolerance), r * Math.sin(Angle + Tolerance)); if ((double) Math.round(Math.sin(Angle) * 10000) / 10000 != 0) { if ((double) Math.round(Math.cos(Angle) * 10000) / 10000 != 0) { double a = (1 + Math.pow(Math.tan(Angle), 2)); double b = 2 * bw / Math.sin(Angle) * Math.pow(Math.tan(Angle), 2); double c = Math.pow(Math.tan(Angle), 2) * Math.pow(bw / Math.sin(Angle), 2) - Math.pow(Radius, 2); double x1 = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a); double y1 = Math.tan(Angle) * (x1 + bw / Math.sin(Angle)); double x2 = (-b - Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a); double y2 = Math.tan(Angle) * (x2 + bw / Math.sin(Angle)); double d1 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2)) + (Math.pow((Radius * Math.sin(Angle) - y1), 2))); double d2 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x2), 2)) + (Math.pow((Radius * Math.sin(Angle) - y2), 2))); if (d1 < d2) { seriesT1.add(x1, y1); } else { seriesT1.add(x2, y2); } } else { double x1 = -bw * Math.sin(Angle); double y1 = Math.sqrt(Math.pow(Radius, 2) - Math.pow(x1, 2)); double y2 = -Math.sqrt(Math.pow(Radius, 2) - Math.pow(x1, 2)); double d1 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2)) + (Math.pow((Radius * Math.sin(Angle) - y1), 2))); double d2 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2)) + (Math.pow((Radius * Math.sin(Angle) - y2), 2))); if (d1 < d2) { seriesT1.add(x1, y1); } else { seriesT1.add(x1, y2); } } } else { double y1 = bw * Math.cos(Angle); double x1 = Math.sqrt(Math.pow(Radius, 2) - Math.pow(y1, 2)); double x2 = -Math.sqrt(Math.pow(Radius, 2) - Math.pow(y1, 2)); double d1 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2)) + (Math.pow((Radius * Math.sin(Angle) - y1), 2))); double d2 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x2), 2)) + (Math.pow((Radius * Math.sin(Angle) - y1), 2))); if (d1 < d2) { seriesT1.add(x1, y1); } else { seriesT1.add(x2, y1); } } AngleCollct.addSeries(seriesT1); XYSeries seriesT2 = new XYSeries("2"); seriesT2.add(r * Math.cos(Angle + Tolerance), r * Math.sin(Angle + Tolerance)); seriesT2.add(0.0, 0.0); AngleCollct.addSeries(seriesT2); XYSeries seriesT3 = new XYSeries("3"); seriesT3.add(Radius * Math.cos(Angle), Radius * Math.sin(Angle)); seriesT3.add(0, 0); AngleCollct.addSeries(seriesT3); XYSeries seriesT4 = new XYSeries("4"); seriesT4.add(r * Math.cos(Angle - Tolerance), r * Math.sin(Angle - Tolerance)); seriesT4.add(0, 0); AngleCollct.addSeries(seriesT4); XYSeries seriesT5 = new XYSeries("5"); seriesT5.add(r * Math.cos(Angle - Tolerance), r * Math.sin(Angle - Tolerance)); if ((double) Math.round(Math.sin(Angle) * 10000) / 10000 != 0) { if ((double) Math.round(Math.cos(Angle) * 10000) / 10000 != 0) { double a = (1 + Math.pow(Math.tan(Angle), 2)); double b = -2 * bw / Math.sin(Angle) * Math.pow(Math.tan(Angle), 2); double c = Math.pow(Math.tan(Angle), 2) * Math.pow(bw / Math.sin(Angle), 2) - Math.pow(Radius, 2); double x1 = (-b + Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a); double y1 = Math.tan(Angle) * (x1 - bw / Math.sin(Angle)); double x2 = (-b - Math.sqrt(Math.pow(b, 2) - 4 * a * c)) / (2 * a); double y2 = Math.tan(Angle) * (x2 - bw / Math.sin(Angle)); double d1 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2)) + (Math.pow((Radius * Math.sin(Angle) - y1), 2))); double d2 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x2), 2)) + (Math.pow((Radius * Math.sin(Angle) - y2), 2))); if (d1 < d2) { seriesT5.add(x1, y1); } else { seriesT5.add(x2, y2); } } else { double x1 = bw * Math.sin(Angle); double y1 = Math.sqrt(Math.pow(Radius, 2) - Math.pow(x1, 2)); double y2 = -Math.sqrt(Math.pow(Radius, 2) - Math.pow(x1, 2)); double d1 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2)) + (Math.pow((Radius * Math.sin(Angle) - y1), 2))); double d2 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2)) + (Math.pow((Radius * Math.sin(Angle) - y2), 2))); if (d1 < d2) { seriesT5.add(x1, y1); } else { seriesT5.add(x1, y2); } } } else { double y1 = -bw * Math.cos(Angle); double x1 = Math.sqrt(Math.pow(Radius, 2) - Math.pow(y1, 2)); double x2 = -Math.sqrt(Math.pow(Radius, 2) - Math.pow(y1, 2)); double d1 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x1), 2)) + (Math.pow((Radius * Math.sin(Angle) - y1), 2))); double d2 = Math.sqrt((Math.pow((Radius * Math.cos(Angle) - x2), 2)) + (Math.pow((Radius * Math.sin(Angle) - y1), 2))); if (d1 < d2) { seriesT5.add(x1, y1); } else { seriesT5.add(x2, y1); } } AngleCollct.addSeries(seriesT5); plot.setDataset(1, AngleCollct); XYLineAndShapeRenderer lineshapRend = new XYLineAndShapeRenderer(true, false); for (int i = 0; i < AngleCollct.getSeriesCount(); i++) { //plot.getRenderer().setSeriesPaint(i , Color.BLUE); lineshapRend.setSeriesPaint(i, Color.BLACK); } plot.setRenderer(1, lineshapRend); combinedrangexyplot.add(plot); } plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); JFreeChart chart = new JFreeChart("Semivariogram Surface", plot); chart.removeLegend(); chart.setBackgroundPaint(Color.white); // create and display a frame... ChartFrame frame = new ChartFrame("", chart); frame.pack(); //frame.setSize(100, 50); frame.setVisible(true); }
From source file:edu.fullerton.viewerplugin.TsPlot.java
@Override public ArrayList<Integer> makePlot(ArrayList<ChanDataBuffer> dbufs, boolean compact) throws WebUtilException { int imageId;// www.ja v a2 s. c om try { if (parameterMap.containsKey("ts_newplt")) { imageId = makeAddPlotFiles(dbufs, compact); } else { String gtitle = getTitle(dbufs, compact); XYSeriesCollection xyds = new XYSeriesCollection(); TimeSeriesCollection mtds = new TimeSeriesCollection(); compact = dbufs.size() > 2 ? false : compact; for (ChanDataBuffer dbuf : dbufs) { if (timeAxis.equalsIgnoreCase("utc")) { addTimeSeries(dbuf, compact, mtds); } else { addXySeries(dbuf, compact, xyds); } } Double minx, miny, maxx, maxy; Double[] rng = new Double[4]; if (timeAxis.equalsIgnoreCase("utc")) { PluginSupport.getRangeLimits(mtds, rng); } else { PluginSupport.getRangeLimits(xyds, rng, 0); } minx = rng[0]; miny = rng[1]; maxx = rng[2]; maxy = rng[3]; int exp; if (timeAxis.equalsIgnoreCase("utc")) { exp = PluginSupport.scaleRange(mtds, miny, maxy); } else { exp = PluginSupport.scaleRange(xyds, miny, maxy); } ChartPanel cpnl; DefaultXYDataset ds = new DefaultXYDataset(); JFreeChart chart; if (timeAxis.equalsIgnoreCase("utc")) { chart = ChartFactory.createTimeSeriesChart(gtitle, "Time (UTC)", "Amplitude (Counts)", ds, true, true, false); } else { chart = ChartFactory.createXYLineChart(gtitle, xAxisLabel, "Amplitude (Counts)", ds, PlotOrientation.VERTICAL, true, false, false); } XYPlot plot = (XYPlot) chart.getPlot(); NumberAxis rangeAxis = new NumberAxis("Amplitude (Counts)"); ScaledAxisNumberFormat sanf = new ScaledAxisNumberFormat(); sanf.setExp(exp); if (maxy != 0 && Math.abs(maxy - miny) <= Math.abs(maxy) * 1e-25) { // this garbage is to get jFreeChart to put labels on the Y axis double dt = Math.abs(miny) / 10; double scaledMin = (miny - dt) * Math.pow(10., exp); double scaledMax = (maxy + dt) * Math.pow(10., exp); rangeAxis.setRange(scaledMin, scaledMax); NumberTickUnit unit = new NumberTickUnit((scaledMax - scaledMin) / 10.); rangeAxis.setTickUnit(unit); rangeAxis.setAutoRange(false); } // else // { // sanf.setMinMax(miny, maxy); // rangeAxis.setRange(miny, maxy); // NumberTickUnit unit = new NumberTickUnit((maxy - miny)/6.); // rangeAxis.setTickUnit(unit); // rangeAxis.setAutoRange(false); // } rangeAxis.setNumberFormatOverride(sanf); rangeAxis.setAutoRangeIncludesZero(false); plot.setRangeAxis(rangeAxis); if (timeAxis.equalsIgnoreCase("utc")) { plot.setDataset(0, mtds); } else { plot.setDataset(0, xyds); } // 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); // add plot.setDomainGridlinesVisible(true); plot.setDomainGridlinePaint(Color.BLACK); plot.setRangeGridlinesVisible(true); plot.setRangeGridlinePaint(Color.BLACK); r.setBaseFillPaint(Color.WHITE); if (compact) { chart.removeLegend(); } chart.setBackgroundPaint(Color.WHITE); cpnl = new ChartPanel(chart); imageId = saveImageAsPNG(cpnl); } } catch (LdvTableException | NoSuchAlgorithmException | SQLException | IOException ex) { throw new WebUtilException("Making time series plot: ", ex); } ArrayList<Integer> ret = new ArrayList<Integer>(); ret.add(imageId); return ret; }