List of usage examples for org.jfree.chart.plot XYPlot getLegendItems
@Override
public LegendItemCollection getLegendItems()
From source file:com.alcatel_lucent.nz.wnmsreport.chart.TimeSeriesIuRChartCustomiser.java
public void customise(JFreeChart chart, JRChart jasperchart) { XYPlot xyplot = chart.getXYPlot(); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyplot.getRenderer(); XYDataset xyDataset = xyplot.getDataset(); LegendItemCollection legend = xyplot.getLegendItems(); LegendItemCollection revised = new LegendItemCollection(); if (xyDataset != null) { for (int i = 0; i < xyDataset.getSeriesCount(); i++) { if (i < 1) { //make line 1 dashed renderer.setSeriesStroke(i, stroke_dashed); } else { //make other lines filled and add to new legend renderer.setSeriesStroke(i, stroke_normal); revised.add(legend.get(i)); }//from ww w . ja v a 2 s . co m renderer.setSeriesLinesVisible(i, true); } } xyplot.setFixedLegendItems(revised); }
From source file:charts.Chart.java
public static void ScatterPlot(XYSeriesCollection dataset, String title, String xAxisLabel, String yAxisLabel) { NumberAxis xAxis = new NumberAxis(xAxisLabel); xAxis.setAutoRangeIncludesZero(false); NumberAxis yAxis = new NumberAxis(yAxisLabel); yAxis.setAutoRangeIncludesZero(false); XYToolTipGenerator toolTipGenerator = new StandardXYToolTipGenerator(); XYURLGenerator urlGenerator = new StandardXYURLGenerator(); XYItemRenderer renderer = new XYLineAndShapeRenderer(false, true);//(boolean lines, boolean shapes) renderer.setBaseToolTipGenerator(toolTipGenerator); renderer.setURLGenerator(urlGenerator); XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer); //plot.setDataset(dataset); //plot.setDomainAxis(xAxis); //plot.setRangeAxis(yAxis); //plot.setRenderer(renderer); plot.setOrientation(PlotOrientation.VERTICAL); plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); plot.setSeriesRenderingOrder(SeriesRenderingOrder.FORWARD); JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);//true==legend //INVERTER AS CORES DOS PONTOS E LEGENDA. if (dataset.getSeriesCount() > 1) { Shape s0 = plot.getLegendItems().get(0).getShape(); Shape s1 = plot.getLegendItems().get(1).getShape(); renderer.setSeriesShape(0, s1);/*from ww w .j a v a 2 s .c o m*/ renderer.setSeriesShape(1, s0); Paint p0 = plot.getLegendItems().get(0).getLinePaint(); Paint p1 = plot.getLegendItems().get(1).getLinePaint(); renderer.setSeriesPaint(0, p1); renderer.setSeriesPaint(1, p0); } //FIM DA INVERSAO. JFrame chartwindow = new JFrame(title); JPanel jpanel = new ChartPanel(chart); jpanel.setPreferredSize(new Dimension(defaultwidth, defaultheight)); chartwindow.setContentPane(jpanel); chartwindow.pack(); RefineryUtilities.centerFrameOnScreen(chartwindow); chartwindow.setVisible(true); }
From source file:ca.nengo.plot.impl.DefaultPlotter.java
/** * @see ca.nengo.plot.Plotter#doPlot(java.util.List, java.util.List, java.lang.String) *///from w w w .jav a 2s . c o m public void doPlot(List<TimeSeries> series, List<SpikePattern> patterns, String title) { JFreeChart chart = ChartFactory.createXYLineChart(title, "Time (s)", "", null, PlotOrientation.VERTICAL, true, false, false); XYPlot plot = (XYPlot) chart.getPlot(); //we will change the legend to show one item per series/pattern (rather than dimension/neuron) LegendItemCollection revisedItems = new LegendItemCollection(); int legendItemIndex = 0; int i = 0; for (; series != null && i < series.size(); i++) { plot.setDataset(i, getDataset(series.get(i))); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false); renderer.setDrawSeriesLineAsPath(true); renderer.setPaint(getColor(i)); plot.setRenderer(i, renderer); String seriesName = series.get(i).getName(); if (seriesName == null) seriesName = "Time Series " + i; revisedItems.add(getCopy(plot.getLegendItems().get(legendItemIndex), seriesName)); legendItemIndex += series.get(i).getDimension(); } for (int j = 0; patterns != null && j < patterns.size(); j++) { int index = i + j; plot.setDataset(index, getDataset(patterns.get(j))); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false); configSpikeRenderer(renderer); renderer.setPaint(getColor(j)); plot.setRenderer(index, renderer); revisedItems.add(getCopy(plot.getLegendItems().get(legendItemIndex), "Spike Pattern " + j)); legendItemIndex += patterns.get(j).getNumNeurons(); } plot.setFixedLegendItems(revisedItems); showChart(chart, title); }
From source file:iDynoOptimizer.MOEAFramework26.src.org.moeaframework.analysis.diagnostics.LinePlot.java
@Override protected void update() { XYDataset dataset = null;/*w w w. j av a 2 s .c om*/ //generate the plot data if (controller.getShowIndividualTraces()) { dataset = new DefaultTableXYDataset(); for (ResultKey key : frame.getSelectedResults()) { generateIndividualSeries(key, (DefaultTableXYDataset) dataset); } } else { dataset = new YIntervalSeriesCollection(); for (ResultKey key : frame.getSelectedResults()) { generateQuantileSeries(key, (YIntervalSeriesCollection) dataset); } } //create the chart JFreeChart chart = ChartFactory.createXYLineChart(metric, localization.getString("text.NFE"), localization.getString("text.value"), dataset, PlotOrientation.VERTICAL, false, true, false); final XYPlot plot = chart.getXYPlot(); //setup the series renderer if (controller.getShowIndividualTraces()) { XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false); for (int i = 0; i < dataset.getSeriesCount(); i++) { Paint paint = frame.getPaintHelper().get(dataset.getSeriesKey(i)); renderer.setSeriesStroke(i, new BasicStroke(1f, 1, 1)); renderer.setSeriesPaint(i, paint); } plot.setRenderer(renderer); } else { DeviationRenderer renderer = new DeviationRenderer(true, false); for (int i = 0; i < dataset.getSeriesCount(); i++) { Paint paint = frame.getPaintHelper().get(dataset.getSeriesKey(i)); renderer.setSeriesStroke(i, new BasicStroke(3f, 1, 1)); renderer.setSeriesPaint(i, paint); renderer.setSeriesFillPaint(i, paint); } plot.setRenderer(renderer); } //create the legend final LegendItemCollection items = plot.getLegendItems(); Iterator<?> iterator = items.iterator(); Set<ResultKey> uniqueKeys = new HashSet<ResultKey>(); while (iterator.hasNext()) { LegendItem item = (LegendItem) iterator.next(); if (uniqueKeys.contains(item.getSeriesKey())) { iterator.remove(); } else { uniqueKeys.add((ResultKey) item.getSeriesKey()); } } LegendItemSource source = new LegendItemSource() { @Override public LegendItemCollection getLegendItems() { return items; } }; LegendTitle legend = new LegendTitle(source); legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0)); legend.setFrame(new LineBorder()); legend.setBackgroundPaint(Color.WHITE); legend.setPosition(RectangleEdge.BOTTOM); chart.addLegend(legend); //scale the axes final NumberAxis domainAxis = new NumberAxis(); domainAxis.setAutoRange(true); plot.setDomainAxis(domainAxis); //add overlay if (controller.getShowLastTrace() && !controller.getShowIndividualTraces() && (controller.getLastAccumulator() != null) && controller.getLastAccumulator().keySet().contains(metric)) { DefaultTableXYDataset dataset2 = new DefaultTableXYDataset(); XYSeries series = new XYSeries(localization.getString("text.last"), false, false); for (int i = 0; i < controller.getLastAccumulator().size(metric); i++) { series.add((Number) controller.getLastAccumulator().get("NFE", i), (Number) controller.getLastAccumulator().get(metric, i)); } dataset2.addSeries(series); XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(true, false); renderer2.setSeriesStroke(0, new BasicStroke(1f, 1, 1)); renderer2.setSeriesPaint(0, Color.BLACK); plot.setDataset(1, dataset2); plot.setRenderer(1, renderer2); plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); } //update the chart in the GUI removeAll(); add(new ChartPanel(chart), BorderLayout.CENTER); revalidate(); repaint(); }
From source file:de.tor.tribes.ui.views.DSWorkbenchStatsFrame.java
private void setupChart(String pInitialId, XYDataset pInitialDataset) { chart = ChartFactory.createTimeSeriesChart("Spielerstatistiken", // title "Zeiten", // x-axis label pInitialId, // y-axis label pInitialDataset, // data jShowLegend.isSelected(), // create legend? true, // generate tooltips? false // generate URLs? );// w w w . jav a 2 s . c o m chart.setBackgroundPaint(Constants.DS_BACK); XYPlot plot = (XYPlot) chart.getPlot(); setupPlotDrawing(plot); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); for (int i = 0; i < plot.getSeriesCount(); i++) { renderer.setSeriesLinesVisible(i, jShowLines.isSelected()); renderer.setSeriesShapesVisible(i, jShowDataPoints.isSelected()); plot.setRenderer(i, renderer); } renderer.setDefaultItemLabelsVisible(jShowItemValues.isSelected()); renderer.setDefaultItemLabelGenerator(new org.jfree.chart.labels.StandardXYItemLabelGenerator()); renderer.setDefaultToolTipGenerator( new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT, new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"), NumberFormat.getInstance())); int lastDataset = plot.getDatasetCount() - 1; if (lastDataset > 0) { plot.getRangeAxis().setAxisLinePaint(plot.getLegendItems().get(lastDataset).getLinePaint()); plot.getRangeAxis().setLabelPaint(plot.getLegendItems().get(lastDataset).getLinePaint()); plot.getRangeAxis().setTickLabelPaint(plot.getLegendItems().get(lastDataset).getLinePaint()); plot.getRangeAxis().setTickMarkPaint(plot.getLegendItems().get(lastDataset).getLinePaint()); } NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(0); nf.setMaximumFractionDigits(0); NumberAxis na = ((NumberAxis) plot.getRangeAxis()); if (na != null) { na.setNumberFormatOverride(nf); } }
From source file:de.tor.tribes.ui.views.DSWorkbenchStatsFrame.java
private void addDataset(String pId, XYDataset pDataset) { if (chart == null) { setupChart(pId, pDataset);/*w w w . j av a 2 s . c om*/ } else { XYPlot plot = (XYPlot) chart.getPlot(); plot.setDataset(plot.getDatasetCount(), pDataset); NumberAxis axis = new NumberAxis(pId); NumberFormat nf = NumberFormat.getInstance(); nf.setMinimumFractionDigits(0); nf.setMaximumFractionDigits(0); axis.setNumberFormatOverride(nf); plot.setRangeAxis(plot.getDatasetCount() - 1, axis); plot.setRangeAxisLocation(plot.getDatasetCount() - 1, AxisLocation.TOP_OR_LEFT); plot.mapDatasetToRangeAxis(plot.getDatasetCount() - 1, plot.getDatasetCount() - 1); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); renderer.setSeriesLinesVisible(0, jShowLines.isSelected()); renderer.setSeriesShapesVisible(0, jShowDataPoints.isSelected()); plot.setRenderer(plot.getDatasetCount() - 1, renderer); renderer.setDefaultItemLabelsVisible(jShowItemValues.isSelected()); renderer.setDefaultItemLabelGenerator(new org.jfree.chart.labels.StandardXYItemLabelGenerator()); renderer.setDefaultToolTipGenerator( new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT, new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"), NumberFormat.getInstance())); axis.setAxisLinePaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint()); axis.setLabelPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint()); axis.setTickLabelPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint()); axis.setTickMarkPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint()); } }
From source file:mil.tatrc.physiology.utilities.csv.plots.RespiratoryPFTPlotter.java
public void createGraph(PlotJob job, Map<String, List<Double>> PFTData, Map<String, 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 < job.headers.size(); i++) { title = title + job.headers.get(i) + "_"; XYSeries dataSeries;/* w w w .java 2s. c om*/ dataSeries = plotTool.createXYSeries(job.headers.get(i), data.get("Time(s)"), data.get(job.headers.get(i))); dataSet.addSeries(dataSeries); maxY = maxY < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY; minY = minY > dataSeries.getMinY() ? dataSeries.getMinY() : minY; } //Now make a data series for PFT data and check its max and min XYSeries dataSeries = plotTool.createXYSeries("PFT Total Lung Volume (mL)", PFTData.get("Time"), PFTData.get("Volume")); dataSet.addSeries(dataSeries); maxY = maxY < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY; minY = minY > dataSeries.getMinY() ? dataSeries.getMinY() : minY; title = title + "vs_Time"; //Override the constructed title if desired 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)); } //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(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength); 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); formatRPFTPlot(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]); } } //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); 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: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; }/* w w w.j ava 2s .c o m*/ 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:gov.llnl.lustre.lwatch.PlotFrame2.java
/** * Define the JFreeChart chart./*w ww . jav a 2 s. com*/ * * @param dataset dataset to be plotted in the chart. */ public JFreeChart createChart(XYDataset dataset) { // Load data for settings from last "Refresh" time String[] selectedRows = lastRefreshPlotParams.getCategories(); String[] selectedVars = lastRefreshPlotParams.getVariables(); String[] selectedCurves = lastRefreshPlotParams.getCurves(); int savedGranularity = granularity; granularity = lastRefreshPlotParams.getGranularity(); boolean showLegend = true; //if (((isAnAggPlot) && (nColsSelected * nCurvesSelected > 8)) || //(nRowsSelected * nColsSelected * nCurvesSelected > 8)) //showLegend = false; if (((isAnAggPlot) && (selectedVars.length * selectedCurves.length > 8)) || (selectedRows.length * selectedVars.length * selectedCurves.length > 8)) showLegend = false; //if (fromRefresh && (nRowsSelected > 0 && nColsSelected > 0 && nCurvesSelected > 0) && //(!noVarSelected)) { if (fromRefresh && (selectedRows.length > 0 && selectedVars.length > 0 && selectedCurves.length > 0) && (!noVarSelected)) { //Debug.out("nRowsSelected = " + nRowsSelected + //" nColsSelected = " + nColsSelected + //" nCurvesSelected = " + nCurvesSelected); pD = new PlotDescriptor(); } chart = ChartFactory.createTimeSeriesChart(fsName + " - " + type + " data", // title "Date", // x-axis label yAxisLabel, // y-axis label dataset, // data showLegend, // create legend false, // generate tooltips false // generate URLs ); chart.setBackgroundPaint(Color.black); //white); // Border color chart.setBorderVisible(true); TextTitle tTitle = chart.getTitle(); tTitle.setPaint(Color.white); XYPlot plot = (XYPlot) chart.getPlot(); plot.setBackgroundPaint(Color.black); //lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.setDomainCrosshairVisible(false); plot.setRangeCrosshairVisible(false); // Check need for logorihmic axis if (useLogRangeAxis) { LogarithmicAxis rangeAxis2 = new LogarithmicAxis(yAxisLabel); plot.setRangeAxis(0, rangeAxis2); } // Default axis annotation is in black. So if the chart background // Paint was set to black above, we need to set axis labels, // tick labels and tick marks to be a contrasting color. plot.getDomainAxis().setLabelPaint(Color.white); plot.getDomainAxis().setTickLabelPaint(Color.white); plot.getDomainAxis().setTickMarkPaint(Color.white); plot.getRangeAxis().setLabelPaint(Color.white); plot.getRangeAxis().setTickLabelPaint(Color.white); plot.getRangeAxis().setTickMarkPaint(Color.white); // Grab the colors from the legend. //int nCurves = nRowsSelected * nColsSelected * nCurvesSelected; int nCurves = selectedRows.length * selectedVars.length * selectedCurves.length; if (localDebug) { Debug.out("selectedRows.length, selectedVars.length, selectedCurves.length = " + selectedRows.length + ", " + selectedVars.length + ", " + selectedCurves.length); Debug.out("Dimension legendColors to size = " + nCurves); } legendColors = new Color[nCurves]; LegendItemCollection lic = plot.getLegendItems(); for (int i = 0; i < lic.getItemCount(); i++) { LegendItem li = lic.get(i); legendColors[i] = (Color) li.getLinePaint(); //if (localDebug) //Debug.out("Line Paint for legend " + i + " = " + //legendColors[i]); } XYItemRenderer r = plot.getRenderer(); if (r instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; renderer.setBaseShapesVisible(showIcons); // Controls icons at data pts. renderer.setBaseShapesFilled(false); } DateAxis axis = (DateAxis) plot.getDomainAxis(); if (granularity == Database.HOUR) axis.setDateFormatOverride(new SimpleDateFormat("MM/dd HH")); //("dd-MMM-yy")); else if (granularity == Database.DAY) axis.setDateFormatOverride(new SimpleDateFormat("MM/dd/yy")); //("dd-MMM-yy")); else if (granularity == Database.WEEK) axis.setDateFormatOverride(new SimpleDateFormat("MM/dd/yy")); //("dd-MMM-yy")); else if (granularity == Database.MONTH) axis.setDateFormatOverride(new SimpleDateFormat("MM/yy")); //("dd-MMM-yy")); else if (granularity == Database.YEAR) axis.setDateFormatOverride(new SimpleDateFormat("yyyy HH:mm")); //("dd-MMM-yy")); else // granualrity == Database.RAW or HEARTBEAT axis.setDateFormatOverride(new SimpleDateFormat("MM/dd HH:mm:ss")); //("dd-MMM-yy")); // Reset granularity; granularity = savedGranularity; return chart; }