List of usage examples for org.jfree.chart.plot XYPlot setDataset
public void setDataset(int index, XYDataset dataset)
From source file:v800_trainer.JHistogram.java
public JPanel StartHistoCd(JCicloTronic JTronicHandle) { boolean Summenhisto; int von = 0;/* w w w . j ava2s .c o m*/ int bis = 0; int num = 0; int selected; int single; int Gruppen = 0; int i = 100; int j = 10; int m = 0; int n = 0; int Linecount = 0; int Anzahl = 1; JFreeChart chart; double DummyData[] = new double[1]; selected = JTronicHandle.Auswahl_Histogramm.getSelectedIndex(); Summenhisto = JTronicHandle.Summenhistogramm_Check.isSelected(); chart = ChartFactory.createHistogram("", "Cadence [n/min]", "Hufigkeit", new HistogramDataset(), PlotOrientation.HORIZONTAL, true, true, true); chart.setBackgroundPaint(Color.white); JTronicHandle.applyChartTheme(chart); XYPlot plot = chart.getXYPlot(); plot.setOrientation(PlotOrientation.VERTICAL); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.getRangeAxis().setFixedDimension(15.0); ArrayList Bufferarray = new ArrayList(); double Buffer; if (selected == 0) { single = 1; } else { single = 0; Summenhisto = false; } try { von = Integer.parseInt(JTronicHandle.Properties.getProperty("HistovonCd", "100")); bis = Integer.parseInt(JTronicHandle.Properties.getProperty("HistobisCd", "200")); Gruppen = Integer.parseInt(JTronicHandle.Properties.getProperty("HistostepCd", "10")); Anzahl = (JTronicHandle.Auswahl_Histogramm.getItemCount() - 2) * single + 1; for (j = 0; j < Anzahl; j++) { if (single == 1) { selected = j + 1; } if (!Summenhisto) { num = JTronicHandle.Statistikhandle.TourData[selected].Datenpunkte; } else { num += JTronicHandle.Statistikhandle.TourData[selected].Datenpunkte; } n = 0; if (!Summenhisto) { create_Start_Stop(JTronicHandle, selected); //die limits einer gezoomten Graphik ermitteln for (i = start; i < stop; i++) { Buffer = (double) JTronicHandle.Statistikhandle.TourData[selected].Cadence_gesZeit[i]; if (Buffer >= von && Buffer <= bis) { Bufferarray.add(Buffer); } } } else { for (i = 0; i < j + 1; i++) { create_Start_Stop(JTronicHandle, i + 1); for (m = start; m < stop; m++) { Buffer = (double) JTronicHandle.Statistikhandle.TourData[i + 1].Cadence_gesZeit[m]; if (Buffer >= von && Buffer <= bis) { Bufferarray.add(Buffer); } } n += m; } } DummyData = new double[Bufferarray.size()]; for (i = 0; i < Bufferarray.size(); i++) { DummyData[i] = new Double(Bufferarray.get(i).toString()); } if (!Summenhisto) { HistogramDataset histoHM = new HistogramDataset(); histoHM.addSeries( "" + JTronicHandle.Statistikhandle.TourData[selected].Tag + "." + JTronicHandle.Statistikhandle.TourData[selected].Monat + "." + JTronicHandle.Statistikhandle.TourData[selected].Jahr, DummyData, Gruppen, (double) von, (double) bis); histoHM.setType(HistogramType.RELATIVE_FREQUENCY); plot.setDataset(Linecount, histoHM); plot.mapDatasetToRangeAxis(Linecount, 0); XYBarRenderer renderer = new XYBarRenderer(); renderer.setDrawBarOutline(true); renderer.setSeriesPaint(0, getColour(Linecount, (int) 255 / Anzahl)); renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); plot.setRenderer(Linecount, renderer); } Linecount++; } } catch (Exception e) { JOptionPane.showMessageDialog(null, "StartHistoCd\nFehler: Cd " + e + " " + i + " " + j, "Achtung!", JOptionPane.ERROR_MESSAGE); } if (Summenhisto) { HistogramDataset histoHM = new HistogramDataset(); histoHM.addSeries("Summenhistogram", DummyData, Gruppen, (double) von, (double) bis); histoHM.setType(HistogramType.RELATIVE_FREQUENCY); plot.setDataset(0, histoHM); plot.mapDatasetToRangeAxis(0, 0); XYItemRenderer renderer = new XYBarRenderer(); renderer.setSeriesPaint(0, Color.blue); renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); plot.setRenderer(0, renderer); } ; chart.setPadding(padding); ChartPanel Panel = new ChartPanel(chart); return Panel; }
From source file:org.ramadda.data.services.PointFormHandler.java
/** * _more_/* w ww . j ava 2 s . c o m*/ * * @param request _more_ * @param pointEntry _more_ * @param plotInfo _more_ * * @return _more_ * * @throws Exception _more_ */ public BufferedImage makeTimeseriesImage(Request request, PointEntry pointEntry, final PlotInfo plotInfo) throws Exception { Entry entry = pointEntry.getEntry(); int width = TIMESERIES_WIDTH; int height = TIMESERIES_HEIGHT; long numRecords = pointEntry.getNumRecords(); final int numPointsToPlot = request.get(ARG_NUMPOINTS, TIMESERIES_POINTS); final int[] cnt = { 0 }; final List<TimeSeries> series = new ArrayList<TimeSeries>(); final List<RecordField> tmpFields = pointEntry.getRecordFile().getChartableFields(); final List<RecordField> fields = new ArrayList<RecordField>(); if (request.get(ARG_CHART_SHOW + FIELD_ALTITUDE, false)) { fields.add(new RecordField(FIELD_ALTITUDE, LABEL_ALTITUDE, "", -1, UNIT_M)); } for (RecordField attr : tmpFields) { if (request.get(ARG_CHART_SHOW + attr.getName(), false)) { fields.add(attr); } } if ((fields.size() == 0) && (tmpFields.size() > 0)) { fields.add(tmpFields.get(0)); request.put(ARG_CHART_SHOW + tmpFields.get(0).getName(), "true"); } for (RecordField attr : fields) { series.add(new TimeSeries(attr.getLabel())); } RecordVisitor visitor = new BridgeRecordVisitor(getOutputHandler()) { public boolean doVisitRecord(RecordFile file, VisitInfo visitInfo, Record record) { PointRecord pointRecord = (PointRecord) record; for (int fieldCnt = 0; fieldCnt < fields.size(); fieldCnt++) { RecordField field = fields.get(fieldCnt); double value; //Check for altitude if (field.getParamId() < 0) { value = pointRecord.getAltitude(); } else { value = record.getValue(field.getParamId()); } long time = record.getRecordTime(); series.get(fieldCnt).add(new FixedMillisecond(time), value); } plotInfo.setIndex(pointRecord.index); cnt[0]++; return true; } }; long t1 = System.currentTimeMillis(); int skip = (int) (numRecords / numPointsToPlot); getRecordJobManager().visitSequential(request, pointEntry, visitor, new VisitInfo(skip)); long t2 = System.currentTimeMillis(); JFreeChart chart = createTimeseriesChart(request, entry, new TimeSeriesCollection(), null); long t3 = System.currentTimeMillis(); XYPlot plot = (XYPlot) chart.getPlot(); int lineCnt = 0; int[] colorCnt = { 0 }; int numberOfAxisLegends = 0; Hashtable<String, double[]> valueRanges = new Hashtable<String, double[]>(); for (int extraCnt = 0; extraCnt < series.size(); extraCnt++) { TimeSeries timeSeries = series.get(extraCnt); RecordField field = fields.get(extraCnt); String unit = field.getUnit(); if ((unit != null) && (unit.length() == 0)) { unit = null; } if (unit == null) { unit = extraCnt + ""; } if (unit == null) { continue; } double max = timeSeries.getMaxY(); double min = timeSeries.getMinY(); double[] range = valueRanges.get(unit); if (range == null) { range = new double[] { min, max }; valueRanges.put(unit, range); } else { range[0] = Math.min(range[0], min); range[1] = Math.max(range[1], max); } } Hashtable<String, NumberAxis> seenAxis = new Hashtable<String, NumberAxis>(); for (int extraCnt = 0; extraCnt < series.size(); extraCnt++) { TimeSeries timeSeries = series.get(extraCnt); RecordField field = fields.get(extraCnt); String unit = field.getUnit(); if ((unit != null) && (unit.length() == 0)) { unit = null; } TimeSeriesCollection dataset2 = new TimeSeriesCollection(); dataset2.addSeries(timeSeries); NumberAxis axis = new NumberAxis(field.getLabel()); numberOfAxisLegends++; if (unit != null) { double[] range = valueRanges.get(unit); axis.setRange(range[0], range[1]); NumberAxis seenOne = seenAxis.get(unit); if (seenOne == null) { seenAxis.put(unit, axis); } else { seenOne.setLabel(seenOne.getLabel() + "/" + field.getLabel()); axis.setVisible(false); numberOfAxisLegends--; } } else { axis.setAutoRange(true); axis.setAutoRangeIncludesZero(true); } plot.setRangeAxis(lineCnt, axis); plot.setDataset(lineCnt, dataset2); plot.mapDatasetToRangeAxis(lineCnt, lineCnt); plot.setRangeAxisLocation(lineCnt, AxisLocation.BOTTOM_OR_RIGHT); StandardXYItemRenderer renderer = new MyStandardXYItemRenderer(plotInfo); renderer.setSeriesPaint(0, getColor(request, ARG_CHART_COLOR + field.getName(), colorCnt)); plot.setRenderer(lineCnt, renderer); lineCnt++; } AxisSpace axisSpace = new AxisSpace(); axisSpace.setRight(TIMESERIES_AXIS_WIDTHPER * numberOfAxisLegends); plot.setFixedRangeAxisSpace(axisSpace); long t4 = System.currentTimeMillis(); BufferedImage newImage = chart.createBufferedImage(width + (numberOfAxisLegends * TIMESERIES_AXIS_WIDTHPER), height); long t5 = System.currentTimeMillis(); // System.err.println("Time series cnt:" + cnt[0] + " " + (t2 - t1) + " " + (t3 - t2) + " " + (t4 - t3) + " " + (t5 - t4)); return newImage; }
From source file:de.bund.bfr.knime.pmm.common.chart.ChartCreator.java
private void plotBothStrict(XYPlot plot, Plotable plotable, String id, double minX, double maxX) throws ConvertException { String legend = shortLegend.get(id); List<Color> colorList = colorLists.get(id); List<Shape> shapeList = shapeLists.get(id); ColorAndShapeCreator creator = new ColorAndShapeCreator(plotable.getNumberOfCombinations()); int index = 0; if (addInfoInLegend) { legend = longLegend.get(id);/*from w ww. j a va 2 s . co m*/ } if (colorList == null || colorList.isEmpty()) { colorList = creator.getColorList(); } if (shapeList == null || shapeList.isEmpty()) { shapeList = creator.getShapeList(); } for (Map<String, Integer> choiceMap : plotable.getAllChoices()) { double[][] dataPoints = plotable.getPoints(paramX, paramY, unitX, unitY, transformX, transformY, choiceMap); if (dataPoints == null) { continue; } double[][] modelPoints = plotable.getFunctionPoints(paramX, paramY, unitX, unitY, transformX, transformY, minX, maxX, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, choiceMap); if (modelPoints == null) { continue; } double[][] modelErrors = null; if (showConfidenceInterval) { modelErrors = plotable.getFunctionErrors(paramX, paramY, unitX, unitY, transformX, transformY, minX, maxX, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, choiceMap); } int i; if (plot.getDataset(0) == null) { i = 0; } else { i = plot.getDatasetCount(); } String addLegend = ""; for (String arg : choiceMap.keySet()) { if (!arg.equals(paramX)) { addLegend += " (" + arg + "=" + plotable.getFunctionArguments().get(arg).get(choiceMap.get(arg)) + ")"; } } if (modelErrors != null) { YIntervalSeriesCollection modelSet = new YIntervalSeriesCollection(); DeviationRenderer modelRenderer = new DeviationRenderer(true, false); YIntervalSeries series = new YIntervalSeries(legend); for (int j = 0; j < modelPoints[0].length; j++) { double error = Double.isNaN(modelErrors[1][j]) ? 0.0 : modelErrors[1][j]; series.add(modelPoints[0][j], modelPoints[1][j], modelPoints[1][j] - error, modelPoints[1][j] + error); } modelSet.addSeries(series); modelRenderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); modelRenderer.setSeriesPaint(0, colorList.get(index)); modelRenderer.setSeriesFillPaint(0, colorList.get(index)); modelRenderer.setSeriesShape(0, shapeList.get(index)); if (dataPoints != null) { modelRenderer.setBaseSeriesVisibleInLegend(false); } plot.setDataset(i, modelSet); plot.setRenderer(i, modelRenderer); } else { DefaultXYDataset modelSet = new DefaultXYDataset(); XYLineAndShapeRenderer modelRenderer = new XYLineAndShapeRenderer(true, false); modelSet.addSeries(legend + addLegend, modelPoints); modelRenderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); modelRenderer.setBaseSeriesVisibleInLegend(false); modelRenderer.setSeriesPaint(0, colorList.get(index)); modelRenderer.setSeriesShape(0, shapeList.get(index)); plot.setDataset(i, modelSet); plot.setRenderer(i, modelRenderer); } DefaultXYDataset dataSet = new DefaultXYDataset(); XYLineAndShapeRenderer dataRenderer = new XYLineAndShapeRenderer(drawLines, true); dataSet.addSeries(legend + addLegend, dataPoints); dataRenderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); dataRenderer.setSeriesPaint(0, colorList.get(index)); dataRenderer.setSeriesShape(0, shapeList.get(index)); plot.setDataset(i + 1, dataSet); plot.setRenderer(i + 1, dataRenderer); index++; } }
From source file:v800_trainer.JHistogram.java
public JPanel StartHistoHf(JCicloTronic JTronicHandle) { boolean Summenhisto; int von = 0;//from w w w . j a v a 2s.co m int bis = 0; int num = 0; int selected; int single; int Gruppen = 0; int i = 100; int j = 10; int m = 0; int n = 0; int Linecount = 0; int Anzahl = 1; JFreeChart chart; double DummyData[] = new double[1]; selected = JTronicHandle.Auswahl_Histogramm.getSelectedIndex(); Summenhisto = JTronicHandle.Summenhistogramm_Check.isSelected(); chart = ChartFactory.createHistogram("", "Herzfrequenz [p/min]", "Hufigkeit", new HistogramDataset(), PlotOrientation.HORIZONTAL, true, true, true); chart.setBackgroundPaint(Color.white); JTronicHandle.applyChartTheme(chart); XYPlot plot = chart.getXYPlot(); plot.setOrientation(PlotOrientation.VERTICAL); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.getRangeAxis().setFixedDimension(15.0); ArrayList Bufferarray = new ArrayList(); double Buffer; if (selected == 0) { single = 1; } else { single = 0; Summenhisto = false; } //einzelne Tour oder alle Touren von = Integer.parseInt(JTronicHandle.Properties.getProperty("HistovonHf", "100")); bis = Integer.parseInt(JTronicHandle.Properties.getProperty("HistobisHf", "200")); Gruppen = Integer.parseInt(JTronicHandle.Properties.getProperty("HistostepHf", "10")); Anzahl = (JTronicHandle.Auswahl_Histogramm.getItemCount() - 2) * single + 1; //komische Mathe; //wenn nur eine Tour ausgewhlt ist single = 0 und damit Anzahl =1 // sonst single gleich 1 und die Anzahl ist ItemCont - 1 for (j = 0; j < Anzahl; j++) { if (single == 1) { selected = j + 1; // single = 1 => Summe ist ausgewhlt und selected muss ein hher gesetz werden } if (!Summenhisto) { num = JTronicHandle.Statistikhandle.TourData[selected].Datenpunkte; } else { num += JTronicHandle.Statistikhandle.TourData[selected].Datenpunkte; } n = 0; if (!Summenhisto) { create_Start_Stop(JTronicHandle, selected); //die limits einer gezoomten Graphik ermitteln for (i = start; i < stop; i++) { //hier wird nun ber alle Daten gezhlt Buffer = (double) JTronicHandle.Statistikhandle.TourData[selected].Hf_gesZeit[i]; //aktueller Wert zwischengespeichert if (Buffer >= von && Buffer <= bis) { Bufferarray.add(Buffer); //wenn im ges. Intervall dann in das Bufferarray } } } else { //Summenhist ist ausgewhlt for (i = 0; i < j + 1; i++) { //schlechte Schleifensteuerung i=1;i<j htte es auch getan create_Start_Stop(JTronicHandle, i + 1); for (m = start; m < stop; m++) { // Schleife ber alle Datenpunkte Buffer = (double) JTronicHandle.Statistikhandle.TourData[i + 1].Hf_gesZeit[m]; if (Buffer >= von && Buffer <= bis) { Bufferarray.add(Buffer); } } } } DummyData = new double[Bufferarray.size()]; for (i = 0; i < Bufferarray.size(); i++) { DummyData[i] = new Double(Bufferarray.get(i).toString()); } if (!Summenhisto) { HistogramDataset histoHF = new HistogramDataset(); histoHF.addSeries( "" + JTronicHandle.Statistikhandle.TourData[selected].Tag + "." + JTronicHandle.Statistikhandle.TourData[selected].Monat + "." + JTronicHandle.Statistikhandle.TourData[selected].Jahr, DummyData, Gruppen, (double) von, (double) bis); histoHF.setType(HistogramType.RELATIVE_FREQUENCY); plot.setDataset(Linecount, histoHF); plot.mapDatasetToRangeAxis(Linecount, 0); XYBarRenderer renderer = new XYBarRenderer(); renderer.setDrawBarOutline(true); // renderer.setShadowVisible(false); renderer.setSeriesPaint(0, getColour(Linecount, (int) 255 / Anzahl)); renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); plot.setRenderer(Linecount, renderer); } Linecount++; } if (Summenhisto) { HistogramDataset histoHF = new HistogramDataset(); histoHF.addSeries("Summenhistogram", DummyData, Gruppen, (double) von, (double) bis); histoHF.setType(HistogramType.RELATIVE_FREQUENCY); plot.setDataset(0, histoHF); plot.mapDatasetToRangeAxis(0, 0); XYItemRenderer renderer = new XYBarRenderer(); renderer.setSeriesPaint(0, Color.blue); renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); plot.setRenderer(0, renderer); } chart.setPadding(padding); ChartPanel Panel = new ChartPanel(chart); return Panel; }
From source file:com.att.aro.ui.view.diagnostictab.plot.GpsPlot.java
@Override public void populate(XYPlot plot, AROTraceData analysis) { if (analysis == null) { logger.info("analysis data is null"); return;/*ww w.j av a 2 s . c o m*/ } gpsData.removeAllSeries(); locationData.removeAllSeries(); TraceResultType resultType = analysis.getAnalyzerResult().getTraceresult().getTraceResultType(); if (resultType.equals(TraceResultType.TRACE_FILE)) { logger.info("didn't get analysis trace data!"); } else { try { image = ImageIO.read(GpsPlot.class.getResourceAsStream("/images/location.png")); image = ImageHelper.resize(image, 12, 12); } catch (IOException e) { e.printStackTrace(); } // create the GPS dataset... Map<GpsState, XYIntervalSeries> seriesMap = new EnumMap<GpsState, XYIntervalSeries>(GpsState.class); for (GpsState eventType : GpsState.values()) { XYIntervalSeries series = new XYIntervalSeries(eventType); seriesMap.put(eventType, series); gpsData.addSeries(series); } series = new XYSeries("location"); TraceDirectoryResult traceresult = (TraceDirectoryResult) analysis.getAnalyzerResult().getTraceresult(); listLocationEvent = (ArrayList<LocationEvent>) traceresult.getLocationEventInfos(); for (int idx = 0; idx < listLocationEvent.size(); idx++) { series.add(listLocationEvent.get(idx).getTimeRecorded(), 0.5); } locationData.addSeries(series); Iterator<GpsInfo> iter = analysis.getAnalyzerResult().getTraceresult().getGpsInfos().iterator(); if (iter.hasNext()) { while (iter.hasNext()) { GpsInfo gpsEvent = iter.next(); if (gpsEvent.getGpsState() != GpsState.GPS_DISABLED) { seriesMap.get(gpsEvent.getGpsState()).add(gpsEvent.getBeginTimeStamp(), gpsEvent.getBeginTimeStamp(), gpsEvent.getEndTimeStamp(), 0.5, 0, 1); } } } XYItemRenderer renderer = plot.getRenderer(0); // 0 - is the default renderer from XYItem renderer. // Looks like renderer is using the index descending order, so setting the index of the GPS background as 2 & location information index as 1. if (renderer == null) { renderer = plot.getRenderer(2); } renderer.setSeriesPaint(gpsData.indexOf(GpsState.GPS_STANDBY), Color.YELLOW); renderer.setSeriesPaint(gpsData.indexOf(GpsState.GPS_ACTIVE), new Color(34, 177, 76)); // Assign ToolTip to renderer renderer.setBaseToolTipGenerator(new XYToolTipGenerator() { @Override public String generateToolTip(XYDataset dataset, int series, int item) { GpsState eventType = (GpsState) gpsData.getSeries(series).getKey(); return MessageFormat.format(ResourceBundleHelper.getMessageString("gps.tooltip"), dataset.getX(series, item), ResourceBundleHelper.getEnumString(eventType)); } }); plot.setRenderer(2, renderer); // Assign ToolTip to renderer LocationImageRenderer renderer_loc = new LocationImageRenderer(); plot.setRenderer(1, renderer_loc); renderer_loc.setBaseToolTipGenerator(new XYToolTipGenerator() { @Override public String generateToolTip(XYDataset dataset, int series, int item) { // Update tooltip of location data LocationEvent event = listLocationEvent.get(item); StringBuffer displayInfo = new StringBuffer( ResourceBundleHelper.getMessageString("location.tooltip.prefix")); displayInfo.append( MessageFormat.format(ResourceBundleHelper.getMessageString("location.tooltip.content"), event.getTimeRecorded(), event.getLatitude(), event.getLongitude(), event.getProvider(), event.getLocality())); displayInfo.append(ResourceBundleHelper.getMessageString("location.tooltip.suffix")); return displayInfo.toString(); } }); } plot.setDataset(2, gpsData); plot.setDataset(1, locationData); }
From source file:mil.tatrc.physiology.utilities.csv.plots.ActionEventPlotter.java
public void createGraph(PlotJob job, List<List<Double>> timeData, List<List<Double>> data, List<LogEvent> events, List<SEAction> actions) { CSVPlotTool plotTool = new CSVPlotTool(); //to leverage existing functions String title = job.name + "_"; XYSeriesCollection dataSet = new XYSeriesCollection(); double maxY = 0; double minY = Double.MAX_VALUE; for (int i = 0; i < timeData.size(); i++) { if (timeData.get(i) == null || data.get(i) == null) { job.bgColor = Color.white; //This hits when we have Expected data but NOT computed data continue; }//from w ww .j a v a2 s .com title = title + job.headers.get(i) + "_"; XYSeries dataSeries; if (job.isComparePlot) { if (timeData.size() > 1) dataSeries = plotTool.createXYSeries(i == 0 ? "Expected" : "Computed", timeData.get(i), data.get(i)); else //If we're comparing but only have one data list, expected is missing, so rename to computed { dataSeries = plotTool.createXYSeries("Computed", timeData.get(i), data.get(i)); } } else dataSeries = plotTool.createXYSeries(job.headers.get(i), timeData.get(i), data.get(i)); dataSet.addSeries(dataSeries); maxY = maxY < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY; minY = minY > dataSeries.getMinY() ? dataSeries.getMinY() : minY; } title = title + "vs_Time_Action_Event_Plot"; //Override the constructed title if desired (usually for compare plots) if (job.titleOverride != null && !job.titleOverride.isEmpty() && !job.titleOverride.equalsIgnoreCase("None")) title = job.titleOverride; double rangeLength = maxY - minY; if (Math.abs(rangeLength) < 1e-6) { rangeLength = .01; } class AEEntry implements Comparable<AEEntry> { public String name; public List<Double> times = new ArrayList<Double>(); public List<Double> YVals = new ArrayList<Double>(); public String type = ""; public int compareTo(AEEntry entry) { return times.get(0) < entry.times.get(0) ? -1 : times.get(0) > entry.times.get(0) ? 1 : 0; } } List<AEEntry> allActionsAndEvents = new ArrayList<AEEntry>(); if (!job.skipAllEvents) { //Make points for each event //Treat each event like two points on the same vertical line for (LogEvent event : events) { boolean skip = false; for (String eventToSkip : job.eventOmissions) { if (event.text.contains(eventToSkip)) skip = true; } if (skip) continue; AEEntry entry = new AEEntry(); entry.times.add(event.time.getValue()); if (job.logAxis) entry.YVals.add(maxY); else if (job.forceZeroYAxisBound && maxY < 0) entry.YVals.add(-.01); else entry.YVals.add(maxY + 0.15 * rangeLength); entry.times.add(event.time.getValue()); if (job.logAxis) entry.YVals.add(minY); else if (job.forceZeroYAxisBound && minY > 0) entry.YVals.add(-.01); else entry.YVals.add(minY - 0.15 * rangeLength); entry.name = event.text + "\r\nt=" + event.time.getValue(); entry.type = "EVENT:"; allActionsAndEvents.add(entry); } } if (!job.skipAllActions) { //Make similar entries for actions for (SEAction action : actions) { boolean skip = false; for (String actionToSkip : job.actionOmissions) { if (action.toString().contains(actionToSkip)) skip = true; } if (skip) continue; if (action.toString().contains("Advance Time")) continue; AEEntry entry = new AEEntry(); entry.times.add(action.getScenarioTime().getValue()); if (job.logAxis) entry.YVals.add(maxY); else if (job.forceZeroYAxisBound && maxY < 0) entry.YVals.add(-.01); else entry.YVals.add(maxY + 0.15 * rangeLength); entry.times.add(action.getScenarioTime().getValue()); if (job.logAxis) entry.YVals.add(minY); else if (job.forceZeroYAxisBound && minY > 0) entry.YVals.add(-.01); else entry.YVals.add(minY - 0.15 * rangeLength); entry.name = action.toString() + "\r\nt=" + action.getScenarioTime().getValue(); entry.type = "ACTION:"; allActionsAndEvents.add(entry); } } //Sort the list Collections.sort(allActionsAndEvents); //Add a series for each entry for (AEEntry entry : allActionsAndEvents) { dataSet.addSeries(plotTool.createXYSeries(entry.type + entry.name, entry.times, entry.YVals)); } //If we have experimental data, try to load it and create a dataset for it XYSeriesCollection expDataSet = new XYSeriesCollection(); if (job.experimentalData != null && !job.experimentalData.isEmpty()) { Map<String, List<Double>> expData = new HashMap<String, List<Double>>(); List<String> expHeaders = new ArrayList<String>(); try { CSVContents csv = new CSVContents(job.experimentalData); csv.abbreviateContents = 0; csv.readAll(expData); expHeaders = csv.getHeaders(); } catch (Exception e) { Log.error("Unable to read experimental data"); } if (!expData.isEmpty() && !expHeaders.isEmpty()) { List<Double> expTimeData = new ArrayList<Double>(); expTimeData = expData.get("Time(s)"); for (String h : expHeaders) //Will assume all headers from exp file will be on same Y axis vs time { if (h.equalsIgnoreCase("Time(s)")) continue; expDataSet.addSeries(plotTool.createXYSeries("Experimental " + h, expTimeData, expData.get(h))); } } } //set labels String XAxisLabel = "Time(s)"; String YAxisLabel = job.headers.get(0); JFreeChart chart = ChartFactory.createXYLineChart( job.titleOverride != null && job.titleOverride.equalsIgnoreCase("None") ? "" : title, // chart title XAxisLabel, // x axis label YAxisLabel, // y axis label dataSet, // data PlotOrientation.VERTICAL, // orientation true, // include legend true, // tooltips false // urls ); Log.info("Creating Graph " + title); XYPlot plot = (XYPlot) chart.getPlot(); if (!job.logAxis) { // Determine Y range double resMax0 = maxY; double resMin0 = minY; if (Double.isNaN(resMax0) || Double.isNaN(resMin0)) plot.getDomainAxis().setLabel("Range is NaN"); if (DoubleUtils.isZero(resMin0)) resMin0 = -0.000001; if (DoubleUtils.isZero(resMax0)) resMax0 = 0.000001; if (job.forceZeroYAxisBound && resMin0 >= 0) resMin0 = -.000001; if (job.forceZeroYAxisBound && resMax0 <= 0) resMax0 = .000001; rangeLength = resMax0 - resMin0; ValueAxis yAxis = plot.getRangeAxis(); if (rangeLength != 0) yAxis.setRange(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength);//15% buffer so we can see top and bottom clearly //Add another Y axis to the right side for easier reading ValueAxis rightYAxis = new NumberAxis(); rightYAxis.setRange(yAxis.getRange()); rightYAxis.setLabel(""); //Override the bounds if desired try { if (job.Y1LowerBound != null) { yAxis.setLowerBound(job.Y1LowerBound); rightYAxis.setLowerBound(job.Y1LowerBound); } if (job.Y1UpperBound != null) { yAxis.setUpperBound(job.Y1UpperBound); rightYAxis.setUpperBound(job.Y1UpperBound); } } catch (Exception e) { Log.error( "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist."); } plot.setRangeAxis(0, yAxis); plot.setRangeAxis(1, rightYAxis); } else { double resMin = minY; double resMax = maxY; if (resMin <= 0.0) resMin = .00001; LogarithmicAxis yAxis = new LogarithmicAxis("Log(" + YAxisLabel + ")"); LogarithmicAxis rightYAxis = new LogarithmicAxis(""); yAxis.setLowerBound(resMin); rightYAxis.setLowerBound(resMin); yAxis.setUpperBound(resMax); rightYAxis.setUpperBound(resMax); //Override the bounds if desired try { if (job.Y1LowerBound != null) { yAxis.setLowerBound(job.Y1LowerBound); rightYAxis.setLowerBound(job.Y1LowerBound); } if (job.Y1UpperBound != null) { yAxis.setUpperBound(job.Y1UpperBound); rightYAxis.setUpperBound(job.Y1UpperBound); } } catch (Exception e) { Log.error( "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist."); } plot.setRangeAxis(0, yAxis); plot.setRangeAxis(1, rightYAxis); } //Override X bounds if desired try { if (job.X1LowerBound != null) plot.getDomainAxis(0).setLowerBound(job.X1LowerBound); if (job.X1UpperBound != null) plot.getDomainAxis(0).setUpperBound(job.X1UpperBound); } catch (Exception e) { Log.error("Couldn't set X bounds. You probably tried to set a bound on an axis that doesn't exist."); } //Override labels if desired if (job.X1Label != null && !plot.getDomainAxis(0).getLabel().contains("NaN")) plot.getDomainAxis(0).setLabel(job.X1Label.equalsIgnoreCase("None") ? "" : job.X1Label); if (job.Y1Label != null) plot.getRangeAxis(0).setLabel(job.Y1Label.equalsIgnoreCase("None") ? "" : job.Y1Label); //If we have experimental data, set up the renderer for it and add to plot if (expDataSet.getSeriesCount() != 0) { XYItemRenderer renderer1 = new XYLineAndShapeRenderer(false, true); // Shapes only renderer1.setSeriesShape(0, ShapeUtilities.createDiamond(8)); plot.setDataset(1, expDataSet); plot.setRenderer(1, renderer1); plot.mapDatasetToDomainAxis(1, 0); plot.mapDatasetToRangeAxis(1, 0); } formatAEPlot(job, chart); plot.setDomainGridlinesVisible(job.showGridLines); plot.setRangeGridlinesVisible(job.showGridLines); //Changing line widths and colors XYItemRenderer r = plot.getRenderer(); BasicStroke wideLine = new BasicStroke(2.0f); Color[] AEcolors = { Color.red, Color.green, Color.black, Color.magenta, Color.orange }; Color[] dataColors = { Color.blue, Color.cyan, Color.gray, Color.black, Color.red }; for (int i = 0, cIndex = 0; i < dataSet.getSeriesCount(); i++, cIndex++) { r.setSeriesStroke(i, wideLine); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); renderer.setBaseShapesVisible(false); if (cIndex > 4) cIndex = 0; if (i < job.headers.size()) //Our actual data { renderer.setSeriesFillPaint(i, dataColors[cIndex]); renderer.setSeriesPaint(i, dataColors[cIndex]); } else //actions and events in procession of other colors { renderer.setSeriesFillPaint(i, AEcolors[cIndex]); renderer.setSeriesPaint(i, AEcolors[cIndex]); } } //Special color and format changes for compare plots if (job.isComparePlot) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); for (int i = 0; i < dataSet.getSeriesCount(); i++) { if (dataSet.getSeries(i).getKey().toString().equalsIgnoreCase("Expected")) { renderer.setSeriesStroke(//makes a dashed line i, //argument below float[]{I,K} -> alternates between solid and opaque (solid for I, opaque for K) new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] { 15.0f, 30.0f }, 0.0f)); renderer.setDrawSeriesLineAsPath(true); renderer.setUseFillPaint(true); renderer.setBaseShapesVisible(false); renderer.setSeriesFillPaint(i, Color.black); renderer.setSeriesPaint(i, Color.black); } if (dataSet.getSeries(i).getKey().toString().equalsIgnoreCase("Computed")) { renderer.setSeriesFillPaint(i, Color.red); renderer.setSeriesPaint(i, Color.red); } if (dataSet.getSeries(i).getKey().toString().startsWith("ACTION")) { renderer.setSeriesFillPaint(i, Color.green); renderer.setSeriesPaint(i, Color.green); } if (dataSet.getSeries(i).getKey().toString().startsWith("EVENT")) { renderer.setSeriesFillPaint(i, Color.blue); renderer.setSeriesPaint(i, Color.blue); } } } //Split the auto-generated legend into two legends, one for data and one for actions and events LegendItemCollection originalLegendCollection = plot.getLegendItems(); final LegendItemCollection dataLegendCollection = new LegendItemCollection(); int i; for (i = 0; i < job.headers.size() && i < originalLegendCollection.getItemCount(); i++) { if (originalLegendCollection.get(i).getLabel().startsWith("ACTION") || originalLegendCollection.get(i).getLabel().startsWith("EVENT")) break; dataLegendCollection.add(originalLegendCollection.get(i)); } final LegendItemCollection remainingLegendCollection = new LegendItemCollection(); for (; i < originalLegendCollection.getItemCount(); i++) { remainingLegendCollection.add(originalLegendCollection.get(i)); } chart.removeLegend(); LegendItemSource source = new LegendItemSource() { LegendItemCollection lic = new LegendItemCollection(); { lic.addAll(dataLegendCollection); } public LegendItemCollection getLegendItems() { return lic; } }; LegendTitle dataLegend = new LegendTitle(source); dataLegend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0)); dataLegend.setBorder(2, 2, 2, 2); dataLegend.setBackgroundPaint(Color.white); dataLegend.setPosition(RectangleEdge.TOP); dataLegend.setItemFont(new Font("SansSerif", Font.PLAIN, 22)); chart.addLegend(dataLegend); source = new LegendItemSource() { LegendItemCollection lic = new LegendItemCollection(); { lic.addAll(remainingLegendCollection); } public LegendItemCollection getLegendItems() { return lic; } }; LegendTitle actionEventsLegend = new LegendTitle(source); actionEventsLegend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0)); actionEventsLegend.setBorder(2, 2, 2, 2); actionEventsLegend.setBackgroundPaint(Color.white); actionEventsLegend.setPosition(RectangleEdge.BOTTOM); actionEventsLegend.setItemFont(new Font("SansSerif", Font.PLAIN, 22)); if (!job.hideAELegend && !job.removeAllLegends) chart.addLegend(actionEventsLegend); if (job.removeAllLegends) chart.removeLegend(); int verticalPixels = 800 + 170 * (allActionsAndEvents.size() / 5); //This is a little hacky, but if we want only the legend, just extend Plot() and remove the draw functionality so it makes a blank plot class legendPlot extends Plot { public void draw(Graphics2D arg0, Rectangle2D arg1, Point2D arg2, PlotState arg3, PlotRenderingInfo arg4) { } public String getPlotType() { return null; } } //Then add the legend to that and throw away the original plot if (job.legendOnly) { chart = new JFreeChart("", null, new legendPlot(), false); chart.addLegend(actionEventsLegend); } try { FileUtils.createDirectory(job.outputDir); String filename = job.outputFilename == null ? job.outputDir + "/" + plotTool.MakeFileName(title) + ".jpg" : job.outputDir + "/" + job.outputFilename; if (!filename.endsWith(".jpg")) filename = filename + ".jpg"; File JPGFile = new File(filename); if (job.imageHeight != null && job.imageWidth != null) ChartUtilities.saveChartAsJPEG(JPGFile, chart, job.imageWidth, job.imageHeight); else if (!job.hideAELegend && !job.removeAllLegends) ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, verticalPixels); else ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, 800); } catch (IOException e) { Log.error(e.getMessage()); } }
From source file:v800_trainer.JUebersicht.java
public JPanel Update_Uebersicht(JCicloTronic JTronicHandle) { int i;/* ww w . j a v a 2s. c o m*/ Day xTime[]; Today = new GregorianCalendar(); double y1Werte[]; double y2Werte[]; double y3Werte[]; double y4Werte[]; double y5Werte[]; double y6Werte[]; double y7Werte[]; double y8Werte[]; double y9Werte[]; double y10Werte[]; double SummeZeit = 0; double Summekm = 0; double Summehm = 0; double SummeZeit12Mon = 0; double Summekm12Mon = 0; double Summehm12Mon = 0; int AnzahlJahre = 0; int Selektiert = 0; int SelektiertVergl = 0; int Jahr; int Linecount = 0; boolean Vergleich = false; XYItemRenderer renderer; XYBarRenderer rendererb; JFreeChart chart; AnzahlJahre = JTronicHandle.Auswahl_bersicht.getItemCount(); Selektiert = JTronicHandle.Auswahl_bersicht.getSelectedIndex(); SelektiertVergl = JTronicHandle.JahrVergleich.getSelectedIndex(); if (SelektiertVergl == 0 || Selektiert == SelektiertVergl - 1) Vergleich = false; else Vergleich = true; xTime = new Day[366]; y1Werte = new double[366]; y2Werte = new double[366]; y3Werte = new double[366]; y4Werte = new double[366]; y5Werte = new double[366]; y6Werte = new double[366]; y7Werte = new double[366]; y8Werte = new double[366]; y9Werte = new double[366]; y10Werte = new double[366]; TimeSeries dataset; dataset = new TimeSeries("dummy"); dataset.add(new Day(1, 1, 1900), 1); TimeSeriesCollection dataset1 = new TimeSeriesCollection(dataset); chart = ChartFactory.createTimeSeriesChart( "Jahresbersicht " + JTronicHandle.Auswahl_bersicht.getSelectedItem().toString(), "Zeit", "", dataset1, true, true, true); XYToolTipGenerator ToolTip = new StandardXYToolTipGenerator("{0}: ({1}, {2})", (DateFormat) new SimpleDateFormat("dd.MM"), NumberFormat.getInstance()); if (SelektiertVergl != 0) chart.addSubtitle(new TextTitle( "Vergleich mit Jahr " + JTronicHandle.JahrVergleich.getSelectedItem().toString())); chart.setBackgroundPaint(Color.white); JTronicHandle.applyChartTheme(chart); XYPlot plot = chart.getXYPlot(); plot.setOrientation(PlotOrientation.VERTICAL); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); plot.setRangeCrosshairLockedOnData(false); plot.setDomainCrosshairLockedOnData(false); if (!JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { DateAxis MyAxis = new DateAxis(); MyAxis = (DateAxis) plot.getDomainAxis(); MyAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); MyAxis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy")); plot.setDomainGridlinesVisible(false); } plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.getRangeAxis().setFixedDimension(15.0); plot.getDomainAxis().setTickLabelInsets(new RectangleInsets(2.0, 1.0, 2.0, 1.0)); Jahr = Integer.parseInt(JTronicHandle.Auswahl_bersicht.getSelectedItem().toString()); for (i = 0; i < 366; i++) { SummeZeit12Mon += (double) Zeit[Selektiert + 1][i]; Summekm12Mon += (double) kmJahr[Selektiert + 1][i]; Summehm12Mon += (double) HmJahr[Selektiert + 1][i]; } y4Werte[0] = SummeZeit12Mon; y5Werte[0] = Summekm12Mon; y6Werte[0] = Summehm12Mon; xTime[0] = new Day(31, 12, Jahr - 1); for (i = 1; i < 366; i++) { try { xTime[i] = new Day(xTime[i - 1].next().getStart()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Exception GregorianCalender " + e, "Achtung!", JOptionPane.ERROR_MESSAGE); } if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { SummeZeit += (double) Zeit[Selektiert][i]; Summekm += (double) kmJahr[Selektiert][i]; Summehm += (double) HmJahr[Selektiert][i]; y1Werte[i] = SummeZeit; y2Werte[i] = Summekm; y3Werte[i] = Summehm; y4Werte[i] = y4Werte[i - 1] - (double) Zeit[Selektiert + 1][i] + (double) Zeit[Selektiert][i]; y5Werte[i] = y5Werte[i - 1] - (double) kmJahr[Selektiert + 1][i] + (double) kmJahr[Selektiert][i]; y6Werte[i] = y6Werte[i - 1] - (double) HmJahr[Selektiert + 1][i] + (double) HmJahr[Selektiert][i]; } else { Day n = new Day(1, xTime[i].getMonth(), xTime[i].getYear()); try { Kalender = new GregorianCalendar(xTime[i].getYear(), xTime[i].getMonth() - 1, 1); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Exception GregorianCalender " + e, "Achtung!", JOptionPane.ERROR_MESSAGE); } int j = (int) Kalender.get(Kalender.DAY_OF_YEAR); for (int m = 0; m < 6; m++) { y1Werte[j + m + 1] += (double) Zeit[Selektiert][i]; y2Werte[j + m + 11] += (double) kmJahr[Selektiert][i]; y3Werte[j + m + 21] += (double) HmJahr[Selektiert][i]; } } } dataset = new TimeSeries("Trainingszeit " + JTronicHandle.Auswahl_bersicht.getSelectedItem().toString()); for (i = 0; i < 366; i++) { dataset.add(xTime[i], y1Werte[i]); } dataset1 = new TimeSeriesCollection(dataset); NumberAxis axis = new NumberAxis(); try { axis = (NumberAxis) plot.getRangeAxis().clone(); } catch (Exception e) { } axis.setLabel("Stunden"); axis.setAutoRangeIncludesZero(true); axis.setLabelPaint(Color.BLACK); axis.setTickLabelPaint(Color.BLACK); plot.setRangeAxis(0, axis); plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_LEFT); plot.setDataset(Linecount, dataset1); plot.mapDatasetToRangeAxis(Linecount, 0); if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { renderer = new StandardXYItemRenderer(2, ToolTip); renderer.setSeriesPaint(0, getColour(Linecount, 255)); plot.setRenderer(Linecount, renderer); } else { rendererb = new XYBarRenderer(); rendererb.setSeriesPaint(0, getColour(Linecount, 150)); rendererb.setShadowVisible(false); rendererb.setDrawBarOutline(false); rendererb.setBarPainter(new StandardXYBarPainter()); plot.setRenderer(Linecount, rendererb); } Linecount++; dataset = new TimeSeries( "Trainingskilometer " + JTronicHandle.Auswahl_bersicht.getSelectedItem().toString()); for (i = 0; i < 366; i++) { dataset.add(xTime[i], y2Werte[i]); } TimeSeriesCollection dataset2 = new TimeSeriesCollection(dataset); NumberAxis axis2 = new NumberAxis(); try { axis2 = (NumberAxis) plot.getRangeAxis().clone(); } catch (Exception e) { } ; axis2.setLabel("Kilometer"); axis2.setAutoRangeIncludesZero(true); axis2.setLabelPaint(Color.BLACK); axis2.setTickLabelPaint(Color.BLACK); plot.setRangeAxis(1, axis2); plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_LEFT); plot.setDataset(Linecount, dataset2); plot.mapDatasetToRangeAxis(Linecount, 1); if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { renderer = new StandardXYItemRenderer(2, ToolTip); renderer.setSeriesPaint(0, getColour(Linecount, 255)); plot.setRenderer(Linecount, renderer); } else { rendererb = new XYBarRenderer(); rendererb.setSeriesPaint(0, getColour(Linecount, 150)); rendererb.setShadowVisible(false); rendererb.setDrawBarOutline(false); rendererb.setBarPainter(new StandardXYBarPainter()); plot.setRenderer(Linecount, rendererb); } Linecount++; dataset = new TimeSeries( "Trainingshhenmeter " + JTronicHandle.Auswahl_bersicht.getSelectedItem().toString()); for (i = 0; i < 366; i++) { dataset.add(xTime[i], y3Werte[i]); } TimeSeriesCollection dataset3 = new TimeSeriesCollection(dataset); NumberAxis axis3 = new NumberAxis("Hhenmeter"); try { axis3 = (NumberAxis) plot.getRangeAxis().clone(); } catch (Exception e) { } ; axis3.setLabel("Hhenmeter"); axis3.setAutoRangeIncludesZero(true); axis3.setLabelPaint(Color.BLACK); axis3.setTickLabelPaint(Color.BLACK); plot.setRangeAxis(2, axis3); plot.setRangeAxisLocation(2, AxisLocation.BOTTOM_OR_RIGHT); plot.setDataset(Linecount, dataset3); plot.mapDatasetToRangeAxis(Linecount, 2); if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { renderer = new StandardXYItemRenderer(2, ToolTip); renderer.setSeriesPaint(0, getColour(Linecount, 255)); plot.setRenderer(Linecount, renderer); } else { rendererb = new XYBarRenderer(); rendererb.setSeriesPaint(0, getColour(Linecount, 150)); rendererb.setShadowVisible(false); rendererb.setDrawBarOutline(false); rendererb.setBarPainter(new StandardXYBarPainter()); plot.setRenderer(Linecount, rendererb); } Linecount++; if (Vergleich == true) { SummeZeit = 0; Summekm = 0; Summehm = 0; SummeZeit12Mon = 0; Summekm12Mon = 0; Summehm12Mon = 0; for (i = 0; i < 366; i++) { SummeZeit12Mon += (double) Zeit[SelektiertVergl - 1][i]; Summekm12Mon += (double) kmJahr[SelektiertVergl - 1][i]; Summehm12Mon += (double) HmJahr[SelektiertVergl - 1][i]; } y4Werte[0] = SummeZeit12Mon; y5Werte[0] = Summekm12Mon; y6Werte[0] = Summehm12Mon; for (i = 1; i < 366; i++) { try { } catch (Exception e) { JOptionPane.showMessageDialog(null, "Exception GregorianCalender " + e, "Achtung!", JOptionPane.ERROR_MESSAGE); } ; if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { SummeZeit += (double) Zeit[SelektiertVergl - 1][i]; Summekm += (double) kmJahr[SelektiertVergl - 1][i]; Summehm += (double) HmJahr[SelektiertVergl - 1][i]; y7Werte[i] = SummeZeit; y8Werte[i] = Summekm; y9Werte[i] = Summehm; y4Werte[i] = y4Werte[i - 1] - (double) Zeit[SelektiertVergl - 1][i] + (double) Zeit[Selektiert][i]; y5Werte[i] = y5Werte[i - 1] - (double) kmJahr[SelektiertVergl - 1][i] + (double) kmJahr[Selektiert][i]; y6Werte[i] = y6Werte[i - 1] - (double) HmJahr[SelektiertVergl - 1][i] + (double) HmJahr[Selektiert][i]; } else { Day n = new Day(1, xTime[i].getMonth(), xTime[i].getYear()); try { Kalender = new GregorianCalendar(xTime[i].getYear(), xTime[i].getMonth() - 1, 1); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Exception GregorianCalender " + e, "Achtung!", JOptionPane.ERROR_MESSAGE); } int j = (int) Kalender.get(Kalender.DAY_OF_YEAR); for (int m = 0; m < 5; m++) { y7Werte[j + m + 4] += (double) Zeit[SelektiertVergl - 1][i]; y8Werte[j + m + 14] += (double) kmJahr[SelektiertVergl - 1][i]; y9Werte[j + m + 24] += (double) HmJahr[SelektiertVergl - 1][i]; } } } if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { dataset = new TimeSeries("Trainingszeit ber 12 Monate "); for (i = 0; i < 366; i++) { dataset.add(xTime[i], y4Werte[i]); } TimeSeriesCollection dataset4 = new TimeSeriesCollection(dataset); plot.setDataset(Linecount, dataset4); plot.mapDatasetToRangeAxis(Linecount, 0); if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { renderer = new StandardXYItemRenderer(2, ToolTip); renderer.setSeriesPaint(0, getColour(Linecount, 255)); plot.setRenderer(Linecount, renderer); } else { rendererb = new XYBarRenderer(); rendererb.setSeriesPaint(0, getColour(Linecount, 150)); rendererb.setShadowVisible(false); rendererb.setBarPainter(new StandardXYBarPainter()); plot.setRenderer(Linecount, rendererb); } Linecount++; dataset = new TimeSeries("Trainingskilometer ber 12 Monate "); for (i = 0; i < 366; i++) { dataset.add(xTime[i], y5Werte[i]); } TimeSeriesCollection dataset5 = new TimeSeriesCollection(dataset); plot.setDataset(Linecount, dataset5); plot.mapDatasetToRangeAxis(Linecount, 1); if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { renderer = new StandardXYItemRenderer(2, ToolTip); renderer.setSeriesPaint(0, getColour(Linecount, 255)); plot.setRenderer(Linecount, renderer); } else { rendererb = new XYBarRenderer(); rendererb.setSeriesPaint(0, getColour(Linecount, 150)); rendererb.setShadowVisible(false); rendererb.setGradientPaintTransformer(null); rendererb.setBarPainter(new StandardXYBarPainter()); plot.setRenderer(Linecount, rendererb); } Linecount++; dataset = new TimeSeries("Trainingshhenmeter ber 12 Monate "); for (i = 0; i < 366; i++) { dataset.add(xTime[i], y6Werte[i]); } TimeSeriesCollection dataset6 = new TimeSeriesCollection(dataset); plot.setDataset(Linecount, dataset6); plot.mapDatasetToRangeAxis(Linecount, 2); if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { renderer = new StandardXYItemRenderer(2, ToolTip); renderer.setSeriesPaint(0, getColour(Linecount, 255)); plot.setRenderer(Linecount, renderer); } else { rendererb = new XYBarRenderer(); rendererb.setSeriesPaint(0, getColour(Linecount, 150)); rendererb.setShadowVisible(false); rendererb.setGradientPaintTransformer(null); rendererb.setBarPainter(new StandardXYBarPainter()); plot.setRenderer(Linecount, rendererb); } } Linecount++; dataset = new TimeSeries("Trainingszeit " + JTronicHandle.JahrVergleich.getSelectedItem().toString()); for (i = 0; i < 366; i++) { dataset.add(xTime[i], y7Werte[i]); } TimeSeriesCollection dataset7 = new TimeSeriesCollection(dataset); plot.setDataset(Linecount, dataset7); plot.mapDatasetToRangeAxis(Linecount, 0); if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { renderer = new StandardXYItemRenderer(2, ToolTip); renderer.setSeriesPaint(0, getColour(Linecount, 255)); plot.setRenderer(Linecount, renderer); } else { rendererb = new XYBarRenderer(); rendererb.setSeriesPaint(0, getColour(Linecount, 150)); rendererb.setShadowVisible(false); rendererb.setGradientPaintTransformer(null); rendererb.setBarPainter(new StandardXYBarPainter()); plot.setRenderer(Linecount, rendererb); } Linecount++; dataset = new TimeSeries( "Trainingskilometer " + JTronicHandle.JahrVergleich.getSelectedItem().toString()); for (i = 0; i < 366; i++) { dataset.add(xTime[i], y8Werte[i]); } TimeSeriesCollection dataset8 = new TimeSeriesCollection(dataset); plot.setDataset(Linecount, dataset8); plot.mapDatasetToRangeAxis(Linecount, 1); if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { renderer = new StandardXYItemRenderer(2, ToolTip); renderer.setSeriesPaint(0, getColour(Linecount, 255)); plot.setRenderer(Linecount, renderer); } else { rendererb = new XYBarRenderer(); rendererb.setSeriesPaint(0, getColour(Linecount, 150)); rendererb.setShadowVisible(false); rendererb.setGradientPaintTransformer(null); rendererb.setBarPainter(new StandardXYBarPainter()); plot.setRenderer(Linecount, rendererb); } Linecount++; dataset = new TimeSeries( "Trainingshhenmeter " + JTronicHandle.JahrVergleich.getSelectedItem().toString()); for (i = 0; i < 366; i++) { dataset.add(xTime[i], y9Werte[i]); } TimeSeriesCollection dataset9 = new TimeSeriesCollection(dataset); plot.setDataset(Linecount, dataset9); plot.mapDatasetToRangeAxis(Linecount, 2); if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { renderer = new StandardXYItemRenderer(2, ToolTip); renderer.setSeriesPaint(0, getColour(Linecount, 255)); plot.setRenderer(Linecount, renderer); } else { rendererb = new XYBarRenderer(); rendererb.setSeriesPaint(0, getColour(Linecount, 150)); rendererb.setShadowVisible(false); rendererb.setGradientPaintTransformer(null); rendererb.setBarPainter(new StandardXYBarPainter()); plot.setRenderer(Linecount, rendererb); } } if (!JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { double max = axis.getRange().getUpperBound(); for (i = 0; i < 12; i++) { try { Kalender = new GregorianCalendar(Integer.parseInt(DataProperty.getProperty("Jahr", "0")), i, 1); } catch (Exception e) { JOptionPane.showMessageDialog(null, "JUebersicht\nException GregorianCalender " + e, "Achtung!", JOptionPane.ERROR_MESSAGE); } y10Werte[Kalender.get(Kalender.DAY_OF_YEAR)] = max; y10Werte[Kalender.get(Kalender.DAY_OF_YEAR) + 1] = 0; } dataset = new TimeSeries(""); for (i = 0; i < 366; i++) { dataset.add(xTime[i], y10Werte[i]); } TimeSeriesCollection dataset10 = new TimeSeriesCollection(dataset); plot.setDataset(Linecount + 1, dataset10); plot.mapDatasetToRangeAxis(Linecount + 1, 0); renderer = new StandardXYItemRenderer(2, ToolTip); renderer.setSeriesPaint(0, Color.white); plot.setRenderer(Linecount + 1, renderer); plot.getDomainAxis().setAutoRange(false); axis.setRange(0, max); } if (JTronicHandle.jRadioButton_jahresverlauf.isSelected()) { axis2.setRange(0, axis2.getRange().getUpperBound() * 1.5); axis3.setRange(0, axis3.getRange().getUpperBound() * 2); plot.setDomainCrosshairValue( (double) new GregorianCalendar(Jahr, Today.get(Today.MONTH), Today.get(Today.DAY_OF_MONTH)) .getTimeInMillis()); } chart.setPadding(padding); ChartPanel Panel = new ChartPanel(chart); Panel.setDismissDelay(100000); return Panel; }
From source file:com.afunms.system.manage.equipManager.java
/** * Creates a sample chart./* w w w .j a va 2s . co m*/ * * @return a sample chart. */ private JFreeChart createChart() { final XYDataset direction = createDirectionDataset(600); final JFreeChart chart = ChartFactory.createTimeSeriesChart("", "", "", direction, true, true, false); final XYPlot plot = chart.getXYPlot(); plot.getDomainAxis().setLowerMargin(0.0); plot.getDomainAxis().setUpperMargin(0.0); plot.setRangeCrosshairVisible(true); plot.setDomainCrosshairVisible(true); plot.setBackgroundPaint(Color.WHITE); plot.setForegroundAlpha(0.8f); plot.setRangeGridlinesVisible(true); plot.setRangeGridlinePaint(Color.darkGray); plot.setDomainGridlinesVisible(true); plot.setDomainGridlinePaint(new Color(139, 69, 19)); XYLineAndShapeRenderer render0 = (XYLineAndShapeRenderer) plot.getRenderer(0); render0.setSeriesPaint(0, Color.BLUE); XYAreaRenderer xyarearenderer = new XYAreaRenderer(); xyarearenderer.setSeriesPaint(1, Color.GREEN); // xyarearenderer.setSeriesFillPaint(1, Color.GREEN); xyarearenderer.setPaint(Color.GREEN); // configure the range axis to display directions... final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setAutoRangeIncludesZero(false); final TickUnits units = new TickUnits(); units.add(new NumberTickUnit(180.0, new CompassFormat())); units.add(new NumberTickUnit(90.0, new CompassFormat())); units.add(new NumberTickUnit(45.0, new CompassFormat())); units.add(new NumberTickUnit(22.5, new CompassFormat())); rangeAxis.setStandardTickUnits(units); // add the wind force with a secondary dataset/renderer/axis plot.setRangeAxis(rangeAxis); final XYItemRenderer renderer2 = new XYAreaRenderer(); final ValueAxis axis2 = new NumberAxis(""); axis2.setRange(0.0, 12.0); xyarearenderer.setSeriesPaint(1, new Color(0, 204, 0)); // xyarearenderer.setSeriesFillPaint(1, Color.GREEN); xyarearenderer.setPaint(Color.GREEN); plot.setDataset(1, createForceDataset(600)); plot.setRenderer(1, xyarearenderer); plot.setRangeAxis(1, axis2); plot.mapDatasetToRangeAxis(1, 1); return chart; }
From source file:org.ramadda.geodata.cdmdata.GridPointOutputHandler.java
/** * Output the timeseries image//from w w w . j a v a 2s. co m * * @param request the request * @param entry the entry * @param f the file * * @return the image * * @throws Exception problem creating image */ private Result outputTimeSeriesImage(Request request, Entry entry, File f) throws Exception { StringBuffer sb = new StringBuffer(); //sb.append(getHeader(request, entry)); sb.append(header(msg("Chart"))); TimeSeriesCollection dummy = new TimeSeriesCollection(); JFreeChart chart = createChart(request, entry, dummy); XYPlot xyPlot = (XYPlot) chart.getPlot(); Hashtable<String, MyTimeSeries> seriesMap = new Hashtable<String, MyTimeSeries>(); List<MyTimeSeries> allSeries = new ArrayList<MyTimeSeries>(); int paramCount = 0; int colorCount = 0; boolean axisLeft = true; Hashtable<String, List<ValueAxis>> axisMap = new Hashtable<String, List<ValueAxis>>(); Hashtable<String, double[]> rangeMap = new Hashtable<String, double[]>(); List<String> units = new ArrayList<String>(); List<String> paramUnits = new ArrayList<String>(); List<String> paramNames = new ArrayList<String>(); long t1 = System.currentTimeMillis(); String contents = IOUtil.readContents(getStorageManager().getFileInputStream(f)); List<String> lines = StringUtil.split(contents, "\n", true, true); String header = lines.get(0); String[] headerToks = header.split(","); for (int i = 0; i < headerToks.length; i++) { paramNames.add(getParamName(headerToks[i])); paramUnits.add(getUnitFromName(headerToks[i])); } boolean hasLevel = paramNames.get(3).equals("vertCoord"); boolean readHeader = false; for (String line : lines) { if (!readHeader) { readHeader = true; continue; } String[] lineTokes = line.split(","); Date date = DateUtil.parse(lineTokes[0]); int startIdx = hasLevel ? 4 : 3; for (int i = startIdx; i < lineTokes.length; i++) { double value = Double.parseDouble(lineTokes[i]); if (value != value) { continue; } List<ValueAxis> axises = null; double[] range = null; String u = paramUnits.get(i); String paramName = paramNames.get(i); String formatName = paramName.replaceAll("_", " "); String formatUnit = ((u == null) || (u.length() == 0)) ? "" : "[" + u + "]"; if (u != null) { axises = axisMap.get(u); range = rangeMap.get(u); if (axises == null) { axises = new ArrayList<ValueAxis>(); range = new double[] { value, value }; rangeMap.put(u, range); axisMap.put(u, axises); units.add(u); } range[0] = Math.min(range[0], value); range[1] = Math.max(range[1], value); } MyTimeSeries series = seriesMap.get(paramName); if (series == null) { paramCount++; TimeSeriesCollection dataset = new TimeSeriesCollection(); series = new MyTimeSeries(formatName, FixedMillisecond.class); allSeries.add(series); ValueAxis rangeAxis = new NumberAxis(formatName + " " + formatUnit); if (axises != null) { axises.add(rangeAxis); } XYItemRenderer renderer = new XYAreaRenderer(XYAreaRenderer.LINES); if (colorCount >= HtmlUtils.COLORS.length) { colorCount = 0; } renderer.setSeriesPaint(0, HtmlUtils.COLORS[colorCount]); colorCount++; xyPlot.setRenderer(paramCount, renderer); xyPlot.setRangeAxis(paramCount, rangeAxis, false); AxisLocation side = (axisLeft ? AxisLocation.TOP_OR_LEFT : AxisLocation.BOTTOM_OR_RIGHT); axisLeft = !axisLeft; xyPlot.setRangeAxisLocation(paramCount, side); dataset.setDomainIsPointsInTime(true); dataset.addSeries(series); seriesMap.put(paramNames.get(i), series); xyPlot.setDataset(paramCount, dataset); xyPlot.mapDatasetToRangeAxis(paramCount, paramCount); } //series.addOrUpdate(new FixedMillisecond(pointData.date),value); TimeSeriesDataItem item = new TimeSeriesDataItem(new FixedMillisecond(date), value); series.addItem(item); } } for (MyTimeSeries timeSeries : allSeries) { timeSeries.finish(); } for (String unit : units) { List<ValueAxis> axises = axisMap.get(unit); double[] range = rangeMap.get(unit); for (ValueAxis rangeAxis : axises) { rangeAxis.setRange(new org.jfree.data.Range(range[0], range[1])); } } long t2 = System.currentTimeMillis(); BufferedImage newImage = chart.createBufferedImage(request.get(ARG_IMAGE_WIDTH, 1000), request.get(ARG_IMAGE_HEIGHT, 400)); long t3 = System.currentTimeMillis(); //System.err.println("timeseries image time:" + (t2 - t1) + " " // + (t3 - t2)); File file = getStorageManager().getTmpFile(request, "point.png"); ImageUtils.writeImageToFile(newImage, file); InputStream is = getStorageManager().getFileInputStream(file); Result result = new Result("", is, "image/png"); return result; }
From source file:com.rapidminer.gui.plotter.charts.MultipleSeriesChartPlotter.java
private JFreeChart createChart() { // create the chart... JFreeChart chart = ChartFactory.createXYLineChart(null, // chart title null, // x axis label null, // y axis label null, // data PlotOrientation.VERTICAL, false, // include legend true, // tooltips false // urls );/*from w ww .j ava2s. c o m*/ chart.setBackgroundPaint(Color.white); // get a reference to the plot for further customization... XYPlot plot = (XYPlot) chart.getPlot(); plot.setBackgroundPaint(Color.WHITE); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.setDomainGridlinePaint(Color.LIGHT_GRAY); plot.setRangeGridlinePaint(Color.LIGHT_GRAY); // domain axis if ((indexAxis >= 0) && (!dataTable.isNominal(indexAxis))) { if ((dataTable.isDate(indexAxis)) || (dataTable.isDateTime(indexAxis))) { DateAxis domainAxis = new DateAxis(dataTable.getColumnName(indexAxis)); domainAxis.setTimeZone(Tools.getPreferredTimeZone()); chart.getXYPlot().setDomainAxis(domainAxis); } } else { plot.getDomainAxis().setStandardTickUnits(NumberAxis.createIntegerTickUnits(Locale.US)); ((NumberAxis) plot.getDomainAxis()).setAutoRangeStickyZero(false); ((NumberAxis) plot.getDomainAxis()).setAutoRangeIncludesZero(false); } ValueAxis xAxis = plot.getDomainAxis(); if (indexAxis > -1) { xAxis.setLabel(getDataTable().getColumnName(indexAxis)); } else { xAxis.setLabel(SERIESINDEX_LABEL); } xAxis.setAutoRange(true); xAxis.setLabelFont(LABEL_FONT_BOLD); xAxis.setTickLabelFont(LABEL_FONT); xAxis.setVerticalTickLabels(isLabelRotating()); if (indexAxis > 0) { if (getRangeForDimension(indexAxis) != null) { xAxis.setRange(getRangeForDimension(indexAxis)); } } else { if (getRangeForName(SERIESINDEX_LABEL) != null) { xAxis.setRange(getRangeForName(SERIESINDEX_LABEL)); } } // renderer and range axis synchronized (dataTable) { int numberOfSelectedColumns = 0; for (int c = 0; c < dataTable.getNumberOfColumns(); c++) { if (getPlotColumn(c)) { if (dataTable.isNumerical(c)) { numberOfSelectedColumns++; } } } int columnCount = 0; for (int c = 0; c < dataTable.getNumberOfColumns(); c++) { if (getPlotColumn(c)) { if (dataTable.isNumerical(c)) { // YIntervalSeries series = new // YIntervalSeries(this.dataTable.getColumnName(c)); XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries series = new XYSeries(dataTable.getColumnName(c)); Iterator<DataTableRow> i = dataTable.iterator(); int index = 1; while (i.hasNext()) { DataTableRow row = i.next(); double value = row.getValue(c); if ((indexAxis >= 0) && (!dataTable.isNominal(indexAxis))) { double indexValue = row.getValue(indexAxis); series.add(indexValue, value); } else { series.add(index++, value); } } dataset.addSeries(series); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); Color color = getColorProvider().getPointColor(1.0d); if (numberOfSelectedColumns > 1) { color = getColorProvider() .getPointColor(columnCount / (double) (numberOfSelectedColumns - 1)); } renderer.setSeriesPaint(0, color); renderer.setSeriesStroke(0, new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); renderer.setSeriesShapesVisible(0, false); NumberAxis yAxis = new NumberAxis(dataTable.getColumnName(c)); if (getRangeForDimension(c) != null) { yAxis.setRange(getRangeForDimension(c)); } else { yAxis.setAutoRange(true); yAxis.setAutoRangeStickyZero(false); yAxis.setAutoRangeIncludesZero(false); } yAxis.setLabelFont(LABEL_FONT_BOLD); yAxis.setTickLabelFont(LABEL_FONT); if (numberOfSelectedColumns > 1) { yAxis.setAxisLinePaint(color); yAxis.setTickMarkPaint(color); yAxis.setLabelPaint(color); yAxis.setTickLabelPaint(color); } plot.setRangeAxis(columnCount, yAxis); plot.setRangeAxisLocation(columnCount, AxisLocation.TOP_OR_LEFT); plot.setDataset(columnCount, dataset); plot.setRenderer(columnCount, renderer); plot.mapDatasetToRangeAxis(columnCount, columnCount); columnCount++; } } } } chart.setBackgroundPaint(Color.white); return chart; }