List of usage examples for org.jfree.chart.axis ValueAxis setLabel
public void setLabel(String label)
From source file:org.utgenome.core.cui.DrawHistogram.java
public void execute() throws Exception { InputStream in = null;/*from ww w. j av a 2 s. c o m*/ if ("-".equals(input)) { _logger.info("reading from STDIN"); in = new StandardInputStream(); } else { _logger.info("reading from " + input); in = new FileInputStream(input); } List<Double> data = new ArrayList<Double>(); BufferedReader dataSetInput = new BufferedReader(new InputStreamReader(in)); int lineCount = 1; try { // read data set boolean cutOffTail = !Double.isNaN(xMax); boolean cutOffHead = !Double.isNaN(xMin); for (String line; (line = dataSetInput.readLine()) != null; lineCount++) { if (lineCount % 100000 == 0) _logger.info(String.format("read %,d data points", lineCount)); if (line.startsWith("#")) continue; double v = Double.parseDouble(line); if (cutOffTail && v > xMax) continue; if (cutOffHead && v < xMin) continue; data.add(v); } double[] value = new double[data.size()]; for (int i = 0; i < data.size(); ++i) { value[i] = data.get(i); } // draw histogram HistogramDataset dataSet = new HistogramDataset(); dataSet.setType(HistogramType.FREQUENCY); dataSet.addSeries("data", value, numBins); JFreeChart chart = ChartFactory.createHistogram(null, null, "Frequency", dataSet, PlotOrientation.VERTICAL, false, false, false); if (title != null) { chart.setTitle(title); } ValueAxis domainAxis = chart.getXYPlot().getDomainAxis(); if (cutOffHead) { domainAxis.setLowerBound(xMin); } if (cutOffTail) { domainAxis.setUpperBound(xMax); } if (xLabel != null) { domainAxis.setLabel(xLabel); } if (yLog) { LogarithmicAxis logAxis = new LogarithmicAxis("Frequency"); logAxis.setAllowNegativesFlag(true); logAxis.setAutoRangeIncludesZero(true); chart.getXYPlot().setRangeAxis(logAxis); } if (!Double.isNaN(yMin)) { chart.getXYPlot().getRangeAxis().setLowerBound(yMin); } if (!Double.isNaN(yMax)) { chart.getXYPlot().getRangeAxis().setUpperBound(yMax); } File outputFile = new File(output); _logger.info("output to " + outputFile); ChartUtilities.saveChartAsPNG(outputFile, chart, width, height); } catch (Exception e) { throw new Exception(String.format("error at line %d: %s", lineCount, e)); } }
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 );// w w w . j av a 2 s . co 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; }
From source file:RDGraphGenerator.java
/** * Creates a sample chart.//from w w w. j a v a 2s . c o m * * @param dataset the dataset for the chart. * * @return A sample chart. */ private JFreeChart createDistChart(String riderID) { String riderName = (String) riders.get(riderID); final JFreeChart chart = ChartFactory.createStackedBarChart(riderName + "'s Distances", // chart title "Month", // domain axis label mainDist, // range axis label (CategoryDataset) riderDistances.get(riderID), // data PlotOrientation.VERTICAL, // the plot orientation true, // legend true, // tooltips false // urls ); GroupedStackedBarRenderer renderer = new GroupedStackedBarRenderer(); KeyToGroupMap map = new KeyToGroupMap("G1"); map.mapKeyToGroup("0", "G1"); map.mapKeyToGroup("1", "G1"); map.mapKeyToGroup("2", "G1"); map.mapKeyToGroup("3", "G1"); renderer.setSeriesToGroupMap(map); renderer.setItemMargin(0.0); Paint p1 = new GradientPaint(0.0f, 0.0f, new Color(0x22, 0x22, 0xFF), 0.0f, 0.0f, new Color(0x88, 0x88, 0xFF)); renderer.setSeriesPaint(0, p1); Paint p2 = new GradientPaint(0.0f, 0.0f, new Color(0x22, 0xFF, 0x22), 0.0f, 0.0f, new Color(0x88, 0xFF, 0x88)); renderer.setSeriesPaint(1, p2); Paint p3 = new GradientPaint(0.0f, 0.0f, new Color(0xFF, 0x22, 0x22), 0.0f, 0.0f, new Color(0xFF, 0x88, 0x88)); renderer.setSeriesPaint(2, p3); Paint p4 = new GradientPaint(0.0f, 0.0f, new Color(0xFF, 0xFF, 0x22), 0.0f, 0.0f, new Color(0xFF, 0xFF, 0x88)); renderer.setSeriesPaint(3, p4); renderer.setGradientPaintTransformer( new StandardGradientPaintTransformer(GradientPaintTransformType.HORIZONTAL)); CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.setRenderer(renderer); plot.setFixedLegendItems(createLegendItems()); ValueAxis va = (ValueAxis) plot.getRangeAxis(); ValueAxis ova = null; try { ova = (ValueAxis) va.clone(); } catch (CloneNotSupportedException cnse) { } ova.setLabel(secondaryDist); ova.setLowerBound(va.getLowerBound() * unitConversion); ova.setUpperBound(va.getUpperBound() * unitConversion); plot.setRangeAxis(1, ova); plot.setRangeAxisLocation(1, AxisLocation.TOP_OR_RIGHT); CategoryAxis ca = plot.getDomainAxis(); ca.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90); //Make around the chart transparent. chart.setBackgroundPaint(null); return chart; }
From source file:org.toobsframework.pres.chart.ChartBuilder.java
public ValueAxis createValueAxis(IRequest componentRequest, RangeAxisDef valueAxisDef, Map params, boolean is3D) { ValueAxis valueAxis; if (is3D) {//from w w w . j av a 2 s.c o m valueAxis = new NumberAxis3D(); } else { valueAxis = new NumberAxis(); } if (valueAxisDef != null) { if (valueAxisDef.getRangeLabel() != null) { valueAxis.setLabel( ChartUtil.evaluateTextLabel(componentRequest, valueAxisDef.getRangeLabel(), params)); if (valueAxisDef.getRangeLabel().getFont() != null) { valueAxis.setLabelFont(ChartUtil.getFont(valueAxisDef.getRangeLabel(), null)); } valueAxis.setLabelPaint(ChartUtil.getColor(valueAxisDef.getRangeLabel().getColor())); } if (valueAxisDef.getIntegerTicks()) { valueAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); } if (valueAxisDef.getNumberFormater() != null) { switch (valueAxisDef.getNumberFormater().getType()) { case AxisDefNumberFormaterType.PERCENT_TYPE: ((NumberAxis) valueAxis).setNumberFormatOverride(NumberFormat.getPercentInstance()); break; case AxisDefNumberFormaterType.CUSTOMBEAN_TYPE: ((NumberAxis) valueAxis).setNumberFormatOverride( (NumberFormat) beanFactory.getBean(valueAxisDef.getCustomFormatBean())); break; } } } return valueAxis; }
From source file:org.kineticsystem.commons.data.demo.panels.AggregationChartPane.java
/** * Constructor./*from w w w .ja va 2 s . c o m*/ * @param source This is the source list being modified ate the same time * by many threads. */ public AggregationChartPane(ActiveList<RandomContact> source) { // Define aggregators. GroupAggregator[] aggregators = new GroupAggregator[] { new ContactsPerContinentAggr(), new AvgAgePerContinentAggr(), new MaxAgePerContinentAggr(), new MinAgePerContinentAggr() }; // Aggregator selector. DefaultComboBoxModel groupComboModel = new DefaultComboBoxModel(aggregators); final JComboBox groupCombo = new JComboBox(groupComboModel); groupCombo.setSelectedIndex(1); groupCombo.setToolTipText("Select an aggregation function."); // Create the dataset. dataset = new DefaultCategoryDataset(); List<Country> countries = RandomContactGenerator.getCountries(); Set<String> continents = new TreeSet<String>(); for (Country country : countries) { continents.add(country.getContinent()); } for (String continent : continents) { dataset.setValue(0, continent, ""); } // Define the aggregated list. groups = new GroupMapping<RandomContact>(source); groups.setAggregator(aggregators[0]); groups.getTarget().addActiveListListener(this); // Create the chart. JFreeChart chart = ChartFactory.createBarChart("", "Continent", groups.getAggregator().toString(), dataset, PlotOrientation.VERTICAL, true, // legend? true, // tooltips? false // URLs? ); final ValueAxis axis = chart.getCategoryPlot().getRangeAxis(); axis.setAutoRange(true); axis.setRange(0, 250); ChartPanel chartPanel = new ChartPanel(chart); // Create the selector. ActionListener groupComboListener = new ActionListener() { public void actionPerformed(ActionEvent e) { JComboBox cb = (JComboBox) e.getSource(); GroupAggregator aggr = (GroupAggregator) cb.getSelectedItem(); groups.setAggregator(aggr); axis.setLabel(aggr.toString()); } }; groupCombo.addActionListener(groupComboListener); // Layout the GUI. Cell cell = new Cell(); TetrisLayout groupTableLayout = new TetrisLayout(2, 1); groupTableLayout.setRowWeight(0, 0); groupTableLayout.setRowWeight(1, 100); setLayout(groupTableLayout); add(groupCombo, cell); add(chartPanel, cell); }
From source file:my.electrochem.ElectrochemUI.java
private void readGPESfile(File fileOpen, ChartPanel chartPanel, boolean overlay) throws FileNotFoundException { ArrayList<Float> potentials = new ArrayList<>(); ArrayList<Float> currents = new ArrayList<>(); BufferedReader br = null;//w ww .j a v a2 s.c o m try { String sCurrentLine; //Path path = FileSystems.getDefault().getPath("libs", "filename.txt"); //br = new BufferedReader(new FileReader(path.toString())); br = new BufferedReader(new FileReader(fileOpen.getAbsolutePath())); String ext = getExtension(fileOpen.getAbsolutePath()); //TODO: 3-column data for DPV/SWV etc. int i = 0; while ((sCurrentLine = br.readLine()) != null) { if ((i != 0) && (i != 1)) { String[] arr = sCurrentLine.split(" "); //System.out.println("Array:"+Arrays.toString(arr)); if (arr.length == 3) { //System.out.println("Potential:"+arr[1]); //System.out.println("Current:"+arr[2]); potentials.add(Float.parseFloat(arr[1])); currents.add(Float.parseFloat(arr[2])); } else if (arr.length == 5) { potentials.add(Float.parseFloat(arr[2])); currents.add(Float.parseFloat(arr[4])); } else if ((arr.length == 4) && (arr[2].equals(arr[0]))) { potentials.add(Float.parseFloat(arr[1])); currents.add(Float.parseFloat(arr[3])); } else { potentials.add(Float.parseFloat(arr[2])); currents.add(Float.parseFloat(arr[3])); } } i++; } System.out.println("potentials:" + potentials); System.out.println("currents:" + currents); //TODO: show technique at the UI //TODO: overlay not possible for different techniques ArrayList<String> labels = getGPESXYlabels(fileOpen, ext); ValueAxis xaxis = chartPanel.getChart().getXYPlot().getDomainAxis(); ValueAxis yaxis = chartPanel.getChart().getXYPlot().getRangeAxis(); xaxis.setLabel(labels.get(0)); yaxis.setLabel(labels.get(1)); XYSeries series = getXYSeriesfromiE(potentials, currents, fileOpen.getName()); if (!overlay) { //System.out.println("no overlay gpes open"); dataset1.removeAllSeries(); } dataset1.addSeries(series); jPanel1.validate(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (br != null) br.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
From source file:org.jivesoftware.openfire.reporting.graph.GraphEngine.java
/** * Generates a Sparkline Bar Graph.//from w ww . j a v a 2 s.c o m * * @param def the key of the statistic object. * @return the generated chart. */ public JFreeChart generateSparklineBarGraph(String key, String color, Statistic[] def, long startTime, long endTime, int dataPoints) { Color backgroundColor = getBackgroundColor(); IntervalXYDataset dataset = (IntervalXYDataset) populateData(key, def, startTime, endTime, dataPoints); JFreeChart chart = ChartFactory.createXYBarChart(null, // chart title null, // domain axis label true, null, // range axis label dataset, // data PlotOrientation.VERTICAL, false, // include legend false, // tooltips? false // URLs? ); chart.setBackgroundPaint(backgroundColor); chart.setBorderVisible(false); chart.setBorderPaint(null); XYPlot plot = (XYPlot) chart.getPlot(); plot.setDomainGridlinesVisible(false); plot.setDomainCrosshairVisible(false); plot.setRangeCrosshairVisible(false); plot.setBackgroundPaint(backgroundColor); plot.setRangeGridlinesVisible(false); GraphDefinition graphDef = GraphDefinition.getDefinition(color); Color plotColor = graphDef.getInlineColor(0); plot.getRenderer().setSeriesPaint(0, plotColor); plot.getRenderer().setBaseItemLabelsVisible(false); plot.getRenderer().setBaseOutlinePaint(backgroundColor); plot.setOutlineStroke(null); plot.setDomainGridlinePaint(null); ValueAxis xAxis = chart.getXYPlot().getDomainAxis(); xAxis.setLabel(null); xAxis.setTickLabelsVisible(true); xAxis.setTickMarksVisible(true); xAxis.setAxisLineVisible(false); xAxis.setNegativeArrowVisible(false); xAxis.setPositiveArrowVisible(false); xAxis.setVisible(false); ValueAxis yAxis = chart.getXYPlot().getRangeAxis(); yAxis.setTickLabelsVisible(false); yAxis.setTickMarksVisible(false); yAxis.setAxisLineVisible(false); yAxis.setNegativeArrowVisible(false); yAxis.setPositiveArrowVisible(false); yAxis.setVisible(false); return chart; }
From source file:desmoj.extensions.visualization2d.engine.modelGrafic.StatisticGrafic.java
/** * some jFreeChart Axis settings for Histogram * @param plot jFreeChart plot instance * @param domainAxisLabel Label of domain Axis *//*from w ww . j a v a2s.com*/ private void buildHistogramAxisFormat(XYPlot plot, String domainAxisLabel) { switch (this.statistic.getTypeData()) { case Statistic.DATA_Observations: ValueAxis rangeAxis = (ValueAxis) plot.getRangeAxis(); rangeAxis.setLabel("Count"); break; case Statistic.DATA_TimeSeries: DateAxis dateAxis = new DateAxis(); DateAxis[] rangeAxisArray = new DateAxis[1]; rangeAxisArray[0] = dateAxis; plot.setRangeAxes(rangeAxisArray); dateAxis = (DateAxis) plot.getRangeAxis(); dateAxis.setMinimumDate(new Date(0)); long diff = dateAxis.getMaximumDate().getTime(); String format, unit; if (diff > 24 * 60 * 60 * 1000) { format = "d.MM.yyyy"; unit = "[day]"; } else if (diff > 60 * 60 * 1000) { format = "H:mm"; unit = "[h]"; } else if (diff > 60 * 1000) { format = "m:ss"; unit = "[min]"; } else if (diff > 1000) { format = "s.S"; unit = "[sec]"; } else { format = "S"; unit = "[millisec]"; } SimpleDateFormat sdf = new SimpleDateFormat(format); dateAxis.setDateFormatOverride(sdf); dateAxis.setLabel("Time " + unit); dateAxis.setLabelFont(Grafic.FONT_DEFAULT); break; } ValueAxis domainAxis = plot.getDomainAxis(); domainAxis.setLabel(domainAxisLabel); /* domainAxis.setLowerBound(statistik.getHistogramLow()); domainAxis.setUpperBound(statistik.getHistogramHigh()); TickUnits tu = new TickUnits(); tu.add(new NumberTickUnit(statistik.getHistogramIntervalLength())); domainAxis.setStandardTickUnits(tu); domainAxis.setAutoTickUnitSelection(true); domainAxis.setVerticalTickLabels(false); */ }
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.java2s . 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:org.kalypso.ogc.sensor.diagview.jfreechart.ObservationPlot.java
/** * Adds a diagram axis and configures it for the use in this plot. * //from w ww.j a v a2s.c o m * @param axis * can be null, if present it is used to define a best suited formatter for the chart axis */ private synchronized void addDiagramAxis(final DiagramAxis diagAxis, final IAxis axis) throws SensorException { if (diagAxis == null) throw new IllegalArgumentException("DiagramAxis is null"); //$NON-NLS-1$ try { final String axisType = axis == null ? null : axis.getType(); final String axisClass = TimeseriesUtils.getAxisClassFor(axisType); if (axisClass == null) { final String msg = String.format( "No Axis-Class defined for type '%s'. Must be defined in timeseries.ini or /KalypsoCore/src/org/kalypso/ogc/sensor/timeseries/resource/config.properties", //$NON-NLS-1$ axisType); throw new SensorException(msg); } final String axisLabel = diagAxis.toFullString(); // Small hack:_ if label is null, we need to instantiate with an string, else the reflection does not work. final String[] arguments = axisLabel == null ? new String[] { "" } : new String[] { axisLabel }; //$NON-NLS-1$ final ValueAxis vAxis = (ValueAxis) ClassUtilities.newInstance(axisClass, ValueAxis.class, ObservationPlot.class.getClassLoader(), arguments); if (axisLabel == null) vAxis.setLabel(null); setTimezone(vAxis); vAxis.setInverted(diagAxis.isInverted()); if (diagAxis.getLowerMargin() != null) vAxis.setLowerMargin(diagAxis.getLowerMargin().doubleValue()); if (diagAxis.getUpperMaring() != null) vAxis.setUpperMargin(diagAxis.getUpperMaring().doubleValue()); final AxisLocation loc = getLocation(diagAxis); if (diagAxis.getDirection().equals(DiagramAxis.DIRECTION_HORIZONTAL)) { final int pos = getAdequateDomainPos(); setDomainAxis(pos, vAxis); setDomainAxisLocation(pos, loc); m_chartAxes2Pos.put(vAxis, new Integer(pos)); } else { final int pos = getAdequateRangePos(); setRangeAxis(pos, vAxis); setRangeAxisLocation(pos, loc); m_chartAxes2Pos.put(vAxis, new Integer(pos)); } m_diag2chartAxis.put(diagAxis, vAxis); } catch (final ClassUtilityException e) { throw new SensorException(e); } }