List of usage examples for org.jfree.chart.title TextTitle setFont
public void setFont(Font font)
From source file:bestdeal.gui.Statistique.java
/** * Creates new form Statistique/*from w w w. j av a 2 s. c o m*/ */ @SuppressWarnings("empty-statement") public Statistique() { initComponents(); btn_retour.setIcon((Icon) new ImageIcon("C:\\Users\\Jedidi\\Desktop\\icone\\retour.png")); panel = new ImagePanel(new ImageIcon("C:\\Users\\Jedidi\\Desktop\\111.jpg").getImage()); Panel.add(panel); lbl_log.setIcon((Icon) new ImageIcon("C:\\Users\\Jedidi\\Desktop\\Logo_.png")); SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); lbl_date1.setText(sdf1.format(new java.util.Date())); SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss"); lbl_heure.setText(sdf2.format(new java.util.Date())); final DefaultPieDataset objDataset = new DefaultPieDataset(); VoucherDAO v2 = new VoucherDAO(); String[][] stat = v2.StatDeal(); objDataset.setValue(stat[0][0], Integer.parseInt(stat[9][0])); objDataset.setValue(stat[0][1], Integer.parseInt(stat[9][1])); objDataset.setValue(stat[0][2], Integer.parseInt(stat[9][2])); objDataset.setValue(stat[0][3], Integer.parseInt(stat[9][3])); objDataset.setValue(stat[0][4], Integer.parseInt(stat[9][4])); JFreeChart objChart = ChartFactory.createPieChart3D("Best 5 deals", objDataset, true, true, true); //String textTitle = "Best 5 deals"; TextTitle textTitle = objChart.getTitle(); textTitle.setFont(new Font("Arial", Font.BOLD, 15)); panel_deals.setLayout(new java.awt.BorderLayout()); panel_clients.setLayout(new java.awt.BorderLayout()); panel_vendeurs.setLayout(new java.awt.BorderLayout()); final ChartPanel CP = new ChartPanel(objChart); CP.setPreferredSize(new java.awt.Dimension(600, 500)); panel_deals.add(CP, BorderLayout.WEST); panel_deals.validate(); TabbedPane.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (TabbedPane.getSelectedIndex() == 0) { objDataset.clear(); VoucherDAO v2 = new VoucherDAO(); String[][] stat = v2.StatDeal(); objDataset.setValue(stat[0][0], Integer.parseInt(stat[9][0])); objDataset.setValue(stat[0][1], Integer.parseInt(stat[9][1])); objDataset.setValue(stat[0][2], Integer.parseInt(stat[9][2])); objDataset.setValue(stat[0][3], Integer.parseInt(stat[9][3])); objDataset.setValue(stat[0][4], Integer.parseInt(stat[9][4])); panel_deals.add(CP, BorderLayout.WEST); panel_deals.validate(); } else if (TabbedPane.getSelectedIndex() == 1) { objDataset.clear(); VoucherDAO v2 = new VoucherDAO(); String[][] stat = v2.StatVendeur(); objDataset.setValue(stat[1][0], Integer.parseInt(stat[7][0])); objDataset.setValue(stat[1][1], Integer.parseInt(stat[7][1])); objDataset.setValue(stat[1][2], Integer.parseInt(stat[7][2])); objDataset.setValue(stat[1][3], Integer.parseInt(stat[7][3])); objDataset.setValue(stat[1][4], Integer.parseInt(stat[7][4])); panel_vendeurs.add(CP, BorderLayout.WEST); panel_vendeurs.validate(); } else if (TabbedPane.getSelectedIndex() == 2) { objDataset.clear(); VoucherDAO v2 = new VoucherDAO(); String[][] stat = v2.StatClient(); objDataset.setValue(stat[1][0], Integer.parseInt(stat[4][0])); objDataset.setValue(stat[1][1], Integer.parseInt(stat[4][1])); objDataset.setValue(stat[1][2], Integer.parseInt(stat[4][2])); objDataset.setValue(stat[1][3], Integer.parseInt(stat[4][3])); objDataset.setValue(stat[1][4], Integer.parseInt(stat[4][4])); panel_clients.add(CP, BorderLayout.WEST); panel_clients.validate(); } else if (TabbedPane.getSelectedIndex() == 3) { } } }); }
From source file:org.openmrs.web.servlet.ShowGraphServlet.java
/** * The main method for this class. It will create a JFreeChart object to be written to the * response.//w ww.ja va 2 s . co m * * @param request the current request will all the parameters needed * @return JFreeChart object to be rendered * @should set value axis label to given units * @should set value axis label to concept numeric units if given units is null */ protected JFreeChart getChart(HttpServletRequest request) { // All available GET parameters String patientId = request.getParameter("patientId"); // required String conceptId1 = request.getParameter("conceptId"); // required String conceptId2 = request.getParameter("conceptId2"); String chartTitle = request.getParameter("chartTitle"); String units = request.getParameter("units"); String minRangeString = request.getParameter("minRange"); String maxRangeString = request.getParameter("maxRange"); String hideDate = request.getParameter("hideDate"); Patient patient = Context.getPatientService().getPatient(Integer.parseInt(patientId)); // Set date range to passed values, otherwise set a default date range to the last 12 months Calendar cal = Calendar.getInstance(); Date fromDate = getFromDate(request.getParameter("fromDate")); Date toDate = getToDate(request.getParameter("toDate")); // Swap if fromDate is after toDate if (fromDate.getTime() > toDate.getTime()) { Long temp = fromDate.getTime(); fromDate.setTime(toDate.getTime()); toDate.setTime(temp); } // Graph parameters Double minRange = null; Double maxRange = null; Double normalLow = null; Double normalHigh = null; Double criticalLow = null; Double criticalHigh = null; String timeAxisTitle = null; String rangeAxisTitle = null; boolean userSpecifiedMaxRange = false; boolean userSpecifiedMinRange = false; // Fetching obs List<Obs> observations1 = new ArrayList<Obs>(); List<Obs> observations2 = new ArrayList<Obs>(); Concept concept1 = null, concept2 = null; if (conceptId1 != null) { concept1 = Context.getConceptService().getConcept(Integer.parseInt(conceptId1)); } if (conceptId2 != null) { concept2 = Context.getConceptService().getConcept(Integer.parseInt(conceptId2)); } if (concept1 != null) { observations1 = Context.getObsService().getObservationsByPersonAndConcept(patient, concept1); chartTitle = concept1.getName().getName(); rangeAxisTitle = ((ConceptNumeric) concept1).getUnits(); minRange = ((ConceptNumeric) concept1).getLowAbsolute(); maxRange = ((ConceptNumeric) concept1).getHiAbsolute(); normalLow = ((ConceptNumeric) concept1).getLowNormal(); normalHigh = ((ConceptNumeric) concept1).getHiNormal(); criticalLow = ((ConceptNumeric) concept1).getLowCritical(); criticalHigh = ((ConceptNumeric) concept1).getHiCritical(); // Only get observations2 if both concepts share the same units; update chart title and ranges if (concept2 != null) { String concept2Units = ((ConceptNumeric) concept2).getUnits(); if (concept2Units != null && concept2Units.equals(rangeAxisTitle)) { observations2 = Context.getObsService().getObservationsByPersonAndConcept(patient, concept2); chartTitle += " + " + concept2.getName().getName(); if (((ConceptNumeric) concept2).getHiAbsolute() != null && ((ConceptNumeric) concept2).getHiAbsolute() > maxRange) { maxRange = ((ConceptNumeric) concept2).getHiAbsolute(); } if (((ConceptNumeric) concept2).getLowAbsolute() != null && ((ConceptNumeric) concept2).getLowAbsolute() < minRange) { minRange = ((ConceptNumeric) concept2).getLowAbsolute(); } } else { log.warn("Units for concept id: " + conceptId2 + " don't match units for concept id: " + conceptId1 + ". Only displaying " + conceptId1); concept2 = null; // nullify concept2 so that the legend isn't shown later } } } else { chartTitle = "Concept " + conceptId1 + " not found"; rangeAxisTitle = "Value"; } // Overwrite with user-specified values, otherwise use default values if (units != null && units.length() > 0) { rangeAxisTitle = units; } if (minRangeString != null) { minRange = Double.parseDouble(minRangeString); userSpecifiedMinRange = true; } if (maxRangeString != null) { maxRange = Double.parseDouble(maxRangeString); userSpecifiedMaxRange = true; } if (chartTitle == null) { chartTitle = ""; } if (rangeAxisTitle == null) { rangeAxisTitle = ""; } if (minRange == null) { minRange = 0.0; } if (maxRange == null) { maxRange = 200.0; } // Create data set TimeSeriesCollection dataset = new TimeSeriesCollection(); TimeSeries series1, series2; // Interval-dependent units Class<? extends RegularTimePeriod> timeScale = null; if (toDate.getTime() - fromDate.getTime() <= 86400000) { // Interval <= 1 day: minutely timeScale = Minute.class; timeAxisTitle = "Time"; } else if (toDate.getTime() - fromDate.getTime() <= 259200000) { // Interval <= 3 days: hourly timeScale = Hour.class; timeAxisTitle = "Time"; } else { timeScale = Day.class; timeAxisTitle = "Date"; } if (concept1 == null) { series1 = new TimeSeries("NULL", Hour.class); } else { series1 = new TimeSeries(concept1.getName().getName(), timeScale); } if (concept2 == null) { series2 = new TimeSeries("NULL", Hour.class); } else { series2 = new TimeSeries(concept2.getName().getName(), timeScale); } // Add data points for concept1 for (Obs obs : observations1) { if (obs.getValueNumeric() != null && obs.getObsDatetime().getTime() >= fromDate.getTime() && obs.getObsDatetime().getTime() < toDate.getTime()) { cal.setTime(obs.getObsDatetime()); if (timeScale == Minute.class) { Minute min = new Minute(cal.get(Calendar.MINUTE), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR)); series1.addOrUpdate(min, obs.getValueNumeric()); } else if (timeScale == Hour.class) { Hour hour = new Hour(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR)); series1.addOrUpdate(hour, obs.getValueNumeric()); } else { Day day = new Day(cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR)); series1.addOrUpdate(day, obs.getValueNumeric()); } } } // Add data points for concept2 for (Obs obs : observations2) { if (obs.getValueNumeric() != null && obs.getObsDatetime().getTime() >= fromDate.getTime() && obs.getObsDatetime().getTime() < toDate.getTime()) { cal.setTime(obs.getObsDatetime()); if (timeScale == Minute.class) { Minute min = new Minute(cal.get(Calendar.MINUTE), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR)); series2.addOrUpdate(min, obs.getValueNumeric()); } else if (timeScale == Hour.class) { Hour hour = new Hour(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR)); series2.addOrUpdate(hour, obs.getValueNumeric()); } else { Day day = new Day(cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH) + 1, cal.get(Calendar.YEAR)); series2.addOrUpdate(day, obs.getValueNumeric()); } } } // Add series to dataset dataset.addSeries(series1); if (!series2.isEmpty()) { dataset.addSeries(series2); } // As of JFreeChart 1.0.11 the default background color is dark grey instead of white. // This line restores the original white background. ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme()); JFreeChart chart = null; // Show legend only if more than one series if (concept2 == null) { chart = ChartFactory.createTimeSeriesChart(chartTitle, timeAxisTitle, rangeAxisTitle, dataset, false, false, false); } else { chart = ChartFactory.createTimeSeriesChart(chartTitle, timeAxisTitle, rangeAxisTitle, dataset, true, false, false); } // Customize title font Font font = new Font("Arial", Font.BOLD, 12); TextTitle title = chart.getTitle(); title.setFont(font); chart.setTitle(title); // Add subtitle, unless 'hideDate' has been passed if (hideDate == null) { TextTitle subtitle = new TextTitle(fromDate.toString() + " - " + toDate.toString()); subtitle.setFont(font); chart.addSubtitle(subtitle); } XYPlot plot = (XYPlot) chart.getPlot(); plot.setNoDataMessage("No Data Available"); // Add abnormal/critical range background color (only for single-concept graphs) if (concept2 == null) { IntervalMarker abnormalLow, abnormalHigh, critical; if (normalHigh != null) { abnormalHigh = new IntervalMarker(normalHigh, maxRange, COLOR_ABNORMAL); plot.addRangeMarker(abnormalHigh); } if (normalLow != null) { abnormalLow = new IntervalMarker(minRange, normalLow, COLOR_ABNORMAL); plot.addRangeMarker(abnormalLow); } if (criticalHigh != null) { critical = new IntervalMarker(criticalHigh, maxRange, COLOR_CRITICAL); plot.addRangeMarker(critical); } if (criticalLow != null) { critical = new IntervalMarker(minRange, criticalLow, COLOR_CRITICAL); plot.addRangeMarker(critical); } // there is data outside of the absolute lower limits for this concept (or of what the user specified as minrange) if (plot.getRangeAxis().getLowerBound() < minRange) { IntervalMarker error = new IntervalMarker(plot.getRangeAxis().getLowerBound(), minRange, COLOR_ERROR); plot.addRangeMarker(error); } if (plot.getRangeAxis().getUpperBound() > maxRange) { IntervalMarker error = new IntervalMarker(maxRange, plot.getRangeAxis().getUpperBound(), COLOR_ERROR); plot.addRangeMarker(error); } } // Visuals XYItemRenderer r = plot.getRenderer(); if (r instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; renderer.setBaseShapesFilled(true); renderer.setBaseShapesVisible(true); } // Customize the plot (range and domain axes) // Modify x-axis (datetime) DateAxis timeAxis = (DateAxis) plot.getDomainAxis(); if (timeScale == Day.class) { timeAxis.setDateFormatOverride(new SimpleDateFormat("dd-MMM-yyyy")); } timeAxis.setRange(fromDate, toDate); // Set y-axis range (values) NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); if (userSpecifiedMinRange) { minRange = (rangeAxis.getLowerBound() < minRange) ? rangeAxis.getLowerBound() : minRange; } if (userSpecifiedMaxRange) { // otherwise we just use default range maxRange = (rangeAxis.getUpperBound() > maxRange) ? rangeAxis.getUpperBound() : maxRange; } rangeAxis.setRange(minRange, maxRange); return chart; }
From source file:weka.classifiers.timeseries.eval.graph.JFreeChartDriver.java
protected JFreeChart getPredictedTargetsChart(TSForecaster forecaster, ErrorModule preds, List<String> targetNames, int stepNumber, int instanceNumOffset, Instances data) { if (forecaster instanceof TSLagUser && data != null) { TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker(); if (lagMaker.getAdjustForTrends() && !lagMaker.isUsingAnArtificialTimeIndex()) { // fill in any missing time stamps only data = new Instances(data); data = weka.classifiers.timeseries.core.Utils.replaceMissing(data, null, lagMaker.getTimeStampField(), true, lagMaker.getPeriodicity(), lagMaker.getSkipEntries()); }/*from w w w.j a v a2 s. com*/ } // set up a collection of predicted and actual series XYIntervalSeriesCollection xyDataset = new XYIntervalSeriesCollection(); for (String target : targetNames) { XYIntervalSeries targetSeries = new XYIntervalSeries(target + "-actual", false, false); xyDataset.addSeries(targetSeries); targetSeries = new XYIntervalSeries(target + "-predicted", false, false); xyDataset.addSeries(targetSeries); } ValueAxis timeAxis = null; NumberAxis valueAxis = new NumberAxis(""); valueAxis.setAutoRangeIncludesZero(false); int timeIndex = -1; boolean timeAxisIsDate = false; if (forecaster instanceof TSLagUser && data != null) { TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker(); if (!lagMaker.isUsingAnArtificialTimeIndex() && lagMaker.getAdjustForTrends()) { String timeName = lagMaker.getTimeStampField(); if (data.attribute(timeName).isDate()) { timeAxis = new DateAxis(""); timeAxisIsDate = true; timeIndex = data.attribute(timeName).index(); } } } if (timeAxis == null) { timeAxis = new NumberAxis(""); ((NumberAxis) timeAxis).setAutoRangeIncludesZero(false); } // now populate the series boolean hasConfidenceIntervals = false; for (int i = 0; i < targetNames.size(); i++) { String targetName = targetNames.get(i); List<NumericPrediction> predsForI = preds.getPredictionsForTarget(targetName); int predIndex = xyDataset.indexOf(targetName + "-predicted"); int actualIndex = xyDataset.indexOf(targetName + "-actual"); XYIntervalSeries predSeries = xyDataset.getSeries(predIndex); XYIntervalSeries actualSeries = xyDataset.getSeries(actualIndex); for (int j = 0; j < predsForI.size(); j++) { double x = Utils.missingValue(); if (timeAxisIsDate) { if (instanceNumOffset + j + stepNumber - 1 < data.numInstances()) { x = data.instance(instanceNumOffset + j + stepNumber - 1).value(timeIndex); } } else { x = instanceNumOffset + j + stepNumber; } double yPredicted = predsForI.get(j).predicted(); double yHigh = yPredicted; double yLow = yPredicted; double[][] conf = predsForI.get(j).predictionIntervals(); if (conf.length > 0) { yLow = conf[0][0]; yHigh = conf[0][1]; hasConfidenceIntervals = true; } if (!Utils.isMissingValue(x) && !Utils.isMissingValue(yPredicted)) { if (predSeries != null) { predSeries.add(x, x, x, yPredicted, yLow, yHigh); } // System.err.println("* " + yPredicted + " " + x); } double yActual = predsForI.get(j).actual(); if (!Utils.isMissingValue(x) && !Utils.isMissingValue(yActual)) { if (actualSeries != null) { actualSeries.add(x, x, x, yActual, yActual, yActual); } } } } // set up the chart String title = "" + stepNumber + " step-ahead predictions for: "; for (String s : targetNames) { title += s + ","; } title = title.substring(0, title.lastIndexOf(",")); /* * String algoSpec = forecaster.getAlgorithmName(); title += " (" + algoSpec * + ")"; */ if (forecaster instanceof WekaForecaster && hasConfidenceIntervals) { double confPerc = ((WekaForecaster) forecaster).getConfidenceLevel() * 100.0; title += " [" + Utils.doubleToString(confPerc, 0) + "% conf. intervals]"; } XYErrorRenderer renderer = new XYErrorRenderer(); renderer.setBaseLinesVisible(true); renderer.setDrawXError(false); renderer.setDrawYError(true); // renderer.setShapesFilled(true); XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, renderer); JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true); chart.setBackgroundPaint(java.awt.Color.white); TextTitle chartTitle = chart.getTitle(); String fontName = chartTitle.getFont().getFontName(); java.awt.Font newFont = new java.awt.Font(fontName, java.awt.Font.PLAIN, 12); chartTitle.setFont(newFont); return chart; }
From source file:weka.classifiers.timeseries.eval.graph.JFreeChartDriver.java
protected JFreeChart getPredictedStepsChart(TSForecaster forecaster, List<ErrorModule> preds, String targetName, List<Integer> stepsToPlot, int instanceNumOffset, Instances data) { if (forecaster instanceof TSLagUser && data != null) { TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker(); if (lagMaker.getAdjustForTrends() && !lagMaker.isUsingAnArtificialTimeIndex()) { // fill in any missing time stamps only data = new Instances(data); data = weka.classifiers.timeseries.core.Utils.replaceMissing(data, null, lagMaker.getTimeStampField(), true, lagMaker.getPeriodicity(), lagMaker.getSkipEntries()); }/*from ww w . ja va 2s . c o m*/ } // set up a collection of predicted series XYIntervalSeriesCollection xyDataset = new XYIntervalSeriesCollection(); XYIntervalSeries targetSeries = new XYIntervalSeries(targetName, false, false); xyDataset.addSeries(targetSeries); // for (int i = 0; i < preds.size(); i++) { for (int z = 0; z < stepsToPlot.size(); z++) { int i = stepsToPlot.get(z); i--; // ignore out of range steps if (i < 0 || i >= preds.size()) { continue; } String step = "-steps"; if (i == 0) { step = "-step"; } targetSeries = new XYIntervalSeries(targetName + "_" + (i + 1) + step + "-ahead", false, false); xyDataset.addSeries(targetSeries); } ValueAxis timeAxis = null; NumberAxis valueAxis = new NumberAxis(""); valueAxis.setAutoRangeIncludesZero(false); int timeIndex = -1; boolean timeAxisIsDate = false; if (forecaster instanceof TSLagUser && data != null) { TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker(); if (!lagMaker.isUsingAnArtificialTimeIndex() && lagMaker.getAdjustForTrends()) { String timeName = lagMaker.getTimeStampField(); if (data.attribute(timeName).isDate()) { timeAxis = new DateAxis(""); timeAxisIsDate = true; timeIndex = data.attribute(timeName).index(); } } } if (timeAxis == null) { timeAxis = new NumberAxis(""); ((NumberAxis) timeAxis).setAutoRangeIncludesZero(false); } // now populate the series // for (int i = 0; i < preds.size(); i++) { boolean doneActual = false; boolean hasConfidenceIntervals = false; for (int z = 0; z < stepsToPlot.size(); z++) { int i = stepsToPlot.get(z); i--; // ignore out of range steps if (i < 0 || i >= preds.size()) { continue; } ErrorModule predsForStepI = preds.get(i); List<NumericPrediction> predsForTargetAtI = predsForStepI.getPredictionsForTarget(targetName); String step = "-steps"; if (i == 0) { step = "-step"; } int predIndex = xyDataset.indexOf(targetName + "_" + (i + 1) + step + "-ahead"); XYIntervalSeries predSeries = xyDataset.getSeries(predIndex); XYIntervalSeries actualSeries = null; if (!doneActual) { int actualIndex = xyDataset.indexOf(targetName); actualSeries = xyDataset.getSeries(actualIndex); } for (int j = 0; j < predsForTargetAtI.size(); j++) { double x = Utils.missingValue(); if (timeAxisIsDate) { if (instanceNumOffset + j + i < data.numInstances()) { x = data.instance(instanceNumOffset + j + i).value(timeIndex); } } else { x = instanceNumOffset + j + i; } double yPredicted = predsForTargetAtI.get(j).predicted(); double yHigh = yPredicted; double yLow = yPredicted; double[][] conf = predsForTargetAtI.get(j).predictionIntervals(); if (conf.length > 0) { yLow = conf[0][0]; yHigh = conf[0][1]; hasConfidenceIntervals = true; } if (!Utils.isMissingValue(x) && !Utils.isMissingValue(yPredicted)) { if (predSeries != null) { predSeries.add(x, x, x, yPredicted, yLow, yHigh); } // System.err.println("* " + yPredicted + " " + x); } if (!doneActual && actualSeries != null) { double yActual = predsForTargetAtI.get(j).actual(); if (!Utils.isMissingValue(x) && !Utils.isMissingValue(yActual)) { actualSeries.add(x, x, x, yActual, yActual, yActual); } } } if (actualSeries != null) { doneActual = true; } } // set up the chart String title = ""; for (int i : stepsToPlot) { title += i + ","; } title = title.substring(0, title.lastIndexOf(",")); title += " step-ahead predictions for " + targetName; /* * String algoSpec = forecaster.getAlgorithmName(); title += " (" + algoSpec * + ")"; */ if (forecaster instanceof WekaForecaster && hasConfidenceIntervals) { double confPerc = ((WekaForecaster) forecaster).getConfidenceLevel() * 100.0; title += " [" + Utils.doubleToString(confPerc, 0) + "% conf. intervals]"; } XYErrorRenderer renderer = new XYErrorRenderer(); renderer.setBaseLinesVisible(true); // renderer.setShapesFilled(true); XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, renderer); JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true); chart.setBackgroundPaint(java.awt.Color.white); TextTitle chartTitle = chart.getTitle(); String fontName = chartTitle.getFont().getFontName(); java.awt.Font newFont = new java.awt.Font(fontName, java.awt.Font.PLAIN, 12); chartTitle.setFont(newFont); return chart; }
From source file:weka.classifiers.timeseries.eval.graph.JFreeChartDriver.java
protected JFreeChart getFutureForecastChart(TSForecaster forecaster, List<List<NumericPrediction>> preds, List<String> targetNames, Instances history) { if (forecaster instanceof TSLagUser && history != null) { TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker(); if (lagMaker.getAdjustForTrends() && !lagMaker.isUsingAnArtificialTimeIndex()) { // fill in any missing time stamps only history = new Instances(history); history = weka.classifiers.timeseries.core.Utils.replaceMissing(history, null, lagMaker.getTimeStampField(), true, lagMaker.getPeriodicity(), lagMaker.getSkipEntries()); }//from ww w . jav a2s. co m } // set up a collection of series XYIntervalSeriesCollection xyDataset = new XYIntervalSeriesCollection(); if (history != null) { // add actual historical data values for (String targetName : targetNames) { XYIntervalSeries targetSeries = new XYIntervalSeries(targetName, false, false); xyDataset.addSeries(targetSeries); } } // add predicted series for (String targetName : targetNames) { XYIntervalSeries targetSeries = new XYIntervalSeries(targetName + "-predicted", false, false); xyDataset.addSeries(targetSeries); } ValueAxis timeAxis = null; NumberAxis valueAxis = new NumberAxis(""); valueAxis.setAutoRangeIncludesZero(false); int timeIndex = -1; boolean timeAxisIsDate = false; double artificialTimeStart = 0; double lastRealTimeValue = Utils.missingValue(); if (forecaster instanceof TSLagUser && history != null) { TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker(); if (!lagMaker.isUsingAnArtificialTimeIndex() && lagMaker.getAdjustForTrends()) { String timeName = lagMaker.getTimeStampField(); if (history.attribute(timeName).isDate()) { timeAxis = new DateAxis(""); timeAxisIsDate = true; timeIndex = history.attribute(timeName).index(); } } else { try { artificialTimeStart = (history != null) ? 1 : lagMaker.getArtificialTimeStartValue() + 1; } catch (Exception ex) { } } } if (timeAxis == null) { timeAxis = new NumberAxis(""); ((NumberAxis) timeAxis).setAutoRangeIncludesZero(false); } boolean hasConfidenceIntervals = false; // now populate the series if (history != null) { // do the actuals first for (int i = 0; i < history.numInstances(); i++) { Instance current = history.instance(i); for (String targetName : targetNames) { int dataIndex = history.attribute(targetName.trim()).index(); if (dataIndex >= 0) { XYIntervalSeries actualSeries = null; int actualIndex = xyDataset.indexOf(targetName); actualSeries = xyDataset.getSeries(actualIndex); double x = Utils.missingValue(); if (timeAxisIsDate) { x = current.value(timeIndex); if (!Utils.isMissingValue(x)) { lastRealTimeValue = x; } } else { x = artificialTimeStart; } double y = Utils.missingValue(); y = current.value(dataIndex); if (!Utils.isMissingValue(x) && !Utils.isMissingValue(y)) { if (actualSeries != null) { actualSeries.add(x, x, x, y, y, y); } } } } if (!timeAxisIsDate) { artificialTimeStart++; } } } // now do the futures List<String> forecasterTargets = AbstractForecaster.stringToList(forecaster.getFieldsToForecast()); // loop over the steps for (int j = 0; j < preds.size(); j++) { List<NumericPrediction> predsForStepJ = preds.get(j); // advance the real time index (if appropriate) if (timeAxisIsDate) { lastRealTimeValue = ((TSLagUser) forecaster).getTSLagMaker() .advanceSuppliedTimeValue(lastRealTimeValue); } for (String targetName : targetNames) { // look up this requested target in the list that the forecaster // has predicted int predIndex = forecasterTargets.indexOf(targetName.trim()); if (predIndex >= 0) { NumericPrediction predsForTargetAtStepJ = predsForStepJ.get(predIndex); XYIntervalSeries predSeries = null; int datasetIndex = xyDataset.indexOf(targetName + "-predicted"); predSeries = xyDataset.getSeries(datasetIndex); if (predSeries != null) { double y = predsForTargetAtStepJ.predicted(); double x = Utils.missingValue(); double yHigh = y; double yLow = y; double[][] conf = predsForTargetAtStepJ.predictionIntervals(); if (conf.length > 0) { yLow = conf[0][0]; yHigh = conf[0][1]; hasConfidenceIntervals = true; } if (!timeAxisIsDate) { x = artificialTimeStart; } else { x = lastRealTimeValue; } if (!Utils.isMissingValue(x) && !Utils.isMissingValue(y)) { predSeries.add(x, x, x, y, yLow, yHigh); } } } } // advance the artificial time index (if appropriate) if (!timeAxisIsDate) { artificialTimeStart++; } } String title = "Future forecast for: "; for (String s : targetNames) { title += s + ","; } title = title.substring(0, title.lastIndexOf(",")); /* * String algoSpec = forecaster.getAlgorithmName(); title += " (" + algoSpec * + ")"; */ if (forecaster instanceof WekaForecaster && hasConfidenceIntervals) { double confPerc = ((WekaForecaster) forecaster).getConfidenceLevel() * 100.0; title += " [" + Utils.doubleToString(confPerc, 0) + "% conf. intervals]"; } XYErrorRenderer renderer = new XYErrorRenderer(); // renderer.setShapesFilled(true); XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, renderer); // renderer = (XYErrorRenderer)plot.getRenderer(); if (history != null) { for (String targetName : targetNames) { XYIntervalSeries predSeries = null; int predIndex = xyDataset.indexOf(targetName + "-predicted"); predSeries = xyDataset.getSeries(predIndex); XYIntervalSeries actualSeries = null; int actualIndex = xyDataset.indexOf(targetName); actualSeries = xyDataset.getSeries(actualIndex); if (actualSeries != null && predSeries != null) { // match the color of the actual series java.awt.Paint actualPaint = renderer.lookupSeriesPaint(actualIndex); renderer.setSeriesPaint(predIndex, actualPaint); // now set the line style to dashed BasicStroke dashed = new BasicStroke(1.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[] { 5.0f }, 0.0f); renderer.setSeriesStroke(predIndex, dashed); } } } renderer.setBaseLinesVisible(true); renderer.setDrawXError(false); renderer.setDrawYError(true); JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true); chart.setBackgroundPaint(java.awt.Color.white); TextTitle chartTitle = chart.getTitle(); String fontName = chartTitle.getFont().getFontName(); java.awt.Font newFont = new java.awt.Font(fontName, java.awt.Font.PLAIN, 12); chartTitle.setFont(newFont); return chart; }
From source file:org.pentaho.di.ui.spoon.trans.TransPerfDelegate.java
private void updateCanvas() { Rectangle bounds = canvas.getBounds(); if (bounds.width <= 0 || bounds.height <= 0) { return;//from www .j ava2 s .co m } // The list of snapshots : convert to JFreeChart dataset // DefaultCategoryDataset dataset = new DefaultCategoryDataset(); String[] selectedSteps = stepsList.getSelection(); if (selectedSteps == null || selectedSteps.length == 0) { selectedSteps = new String[] { steps[0], }; // first step stepsList.select(0); } int[] dataIndices = dataList.getSelectionIndices(); if (dataIndices == null || dataIndices.length == 0) { dataIndices = new int[] { DATA_CHOICE_WRITTEN, }; dataList.select(0); } boolean multiStep = stepsList.getSelectionCount() > 1; boolean multiData = dataList.getSelectionCount() > 1; boolean calcMoving = !multiStep && !multiData; // A single metric shown for a single step List<Double> movingList = new ArrayList<Double>(); int movingSize = 10; double movingTotal = 0; int totalTimeInSeconds = 0; for (int t = 0; t < selectedSteps.length; t++) { String stepNameCopy = selectedSteps[t]; List<StepPerformanceSnapShot> snapShotList = stepPerformanceSnapShots.get(stepNameCopy); if (snapShotList != null && snapShotList.size() > 1) { totalTimeInSeconds = (int) Math .round(((double) (snapShotList.get(snapShotList.size() - 1).getDate().getTime() - snapShotList.get(0).getDate().getTime())) / 1000); for (int i = 0; i < snapShotList.size(); i++) { StepPerformanceSnapShot snapShot = snapShotList.get(i); if (snapShot.getTimeDifference() != 0) { double factor = (double) 1000 / (double) snapShot.getTimeDifference(); for (int d = 0; d < dataIndices.length; d++) { String dataType; if (multiStep) { dataType = stepNameCopy; } else { dataType = dataChoices[dataIndices[d]]; } String xLabel = Integer.toString(Math.round(i * timeDifference / 1000)); Double metric = null; switch (dataIndices[d]) { case DATA_CHOICE_INPUT: metric = snapShot.getLinesInput() * factor; break; case DATA_CHOICE_OUTPUT: metric = snapShot.getLinesOutput() * factor; break; case DATA_CHOICE_READ: metric = snapShot.getLinesRead() * factor; break; case DATA_CHOICE_WRITTEN: metric = snapShot.getLinesWritten() * factor; break; case DATA_CHOICE_UPDATED: metric = snapShot.getLinesUpdated() * factor; break; case DATA_CHOICE_REJECTED: metric = snapShot.getLinesRejected() * factor; break; case DATA_CHOICE_INPUT_BUFFER_SIZE: metric = (double) snapShot.getInputBufferSize(); break; case DATA_CHOICE_OUTPUT_BUFFER_SIZE: metric = (double) snapShot.getOutputBufferSize(); break; default: break; } if (metric != null) { dataset.addValue(metric, dataType, xLabel); if (calcMoving) { movingTotal += metric; movingList.add(metric); if (movingList.size() > movingSize) { movingTotal -= movingList.get(0); movingList.remove(0); } double movingAverage = movingTotal / movingList.size(); dataset.addValue(movingAverage, dataType + "(Avg)", xLabel); // System.out.println("moving average = "+movingAverage+", movingTotal="+movingTotal+", m"); } } } } } } } String chartTitle = title; if (multiStep) { chartTitle += " (" + dataChoices[dataIndices[0]] + ")"; } else { chartTitle += " (" + selectedSteps[0] + ")"; } final JFreeChart chart = ChartFactory.createLineChart(chartTitle, // chart title BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.TimeInSeconds.Label", Integer.toString(totalTimeInSeconds), Long.toString(timeDifference)), // domain axis label BaseMessages.getString(PKG, "StepPerformanceSnapShotDialog.RowsPerSecond.Label"), // range axis label dataset, // data PlotOrientation.VERTICAL, // orientation true, // include legend true, // tooltips false); // urls chart.setBackgroundPaint(Color.white); TextTitle title = new TextTitle(chartTitle); // title.setExpandToFitSpace(true); // org.eclipse.swt.graphics.Color pentahoColor = GUIResource.getInstance().getColorPentaho(); // java.awt.Color color = new java.awt.Color(pentahoColor.getRed(), pentahoColor.getGreen(),pentahoColor.getBlue()); // title.setBackgroundPaint(color); title.setFont(new java.awt.Font("SansSerif", java.awt.Font.BOLD, 12)); chart.setTitle(title); CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.setBackgroundPaint(Color.white); plot.setForegroundAlpha(0.5f); plot.setRangeGridlinesVisible(true); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setTickLabelsVisible(false); // Customize the renderer... // LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer(); renderer.setBaseShapesVisible(true); renderer.setDrawOutlines(true); renderer.setUseFillPaint(true); renderer.setBaseFillPaint(Color.white); renderer.setSeriesStroke(0, new BasicStroke(1.5f)); renderer.setSeriesOutlineStroke(0, new BasicStroke(1.5f)); renderer.setSeriesStroke(1, new BasicStroke(2.5f)); renderer.setSeriesOutlineStroke(1, new BasicStroke(2.5f)); renderer.setSeriesShape(0, new Ellipse2D.Double(-3.0, -3.0, 6.0, 6.0)); BufferedImage bufferedImage = chart.createBufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_RGB, null); ImageData imageData = ImageUtil.convertToSWT(bufferedImage); // dispose previous image... // if (image != null) { image.dispose(); } image = new Image(transGraph.getDisplay(), imageData); // Draw the image on the canvas... // canvas.redraw(); }
From source file:org.esa.beam.visat.toolviews.stat.ScatterPlotPanel.java
private void computeCoefficientOfDetermination() { int numberOfItems = scatterpointsDataset.getSeries(0).getItemCount(); double arithmeticMeanOfX = 0; //arithmetic mean of X double arithmeticMeanOfY = 0; //arithmetic mean of Y double varX = 0; //variance of X double varY = 0; //variance of Y double coVarXY = 0; //covariance of X and Y; //compute arithmetic means for (int i = 0; i < numberOfItems; i++) { arithmeticMeanOfX += scatterpointsDataset.getXValue(0, i); arithmeticMeanOfY += scatterpointsDataset.getYValue(0, i); }/*from w w w . java2 s . c om*/ arithmeticMeanOfX /= numberOfItems; arithmeticMeanOfY /= numberOfItems; //compute variances and covariance for (int i = 0; i < numberOfItems; i++) { varX += Math.pow(scatterpointsDataset.getXValue(0, i) - arithmeticMeanOfX, 2); varY += Math.pow(scatterpointsDataset.getYValue(0, i) - arithmeticMeanOfY, 2); coVarXY += (scatterpointsDataset.getXValue(0, i) - arithmeticMeanOfX) * (scatterpointsDataset.getYValue(0, i) - arithmeticMeanOfY); } //computation of coefficient of determination double r2 = Math.pow(coVarXY, 2) / (varX * varY); r2 = MathUtils.round(r2, Math.pow(10.0, 5)); final double[] coefficients = Regression.getOLSRegression(scatterpointsDataset, 0); final double intercept = coefficients[0]; final double slope = coefficients[1]; final String linearEquation; if (intercept >= 0) { linearEquation = "y = " + (float) slope + "x + " + (float) intercept; } else { linearEquation = "y = " + (float) slope + "x - " + Math.abs((float) intercept); } TextTitle tt = new TextTitle(linearEquation + "\nR = " + r2); tt.setTextAlignment(HorizontalAlignment.RIGHT); tt.setFont(chart.getLegend().getItemFont()); tt.setBackgroundPaint(new Color(200, 200, 255, 100)); tt.setFrame(new BlockBorder(Color.white)); tt.setPosition(RectangleEdge.BOTTOM); r2Annotation = new XYTitleAnnotation(0.98, 0.02, tt, RectangleAnchor.BOTTOM_RIGHT); r2Annotation.setMaxWidth(0.48); getPlot().addAnnotation(r2Annotation); }
From source file:org.jfree.eastwood.ChartEngine.java
/** * Creates and returns a new <code>JFreeChart</code> instance that * reflects the specified parameters (which should be equivalent to * a parameter map returned by HttpServletRequest.getParameterMap() for * a valid URI for the Google Chart API. * * @param params the parameters (<code>null</code> not permitted). * @param font the font to use to draw titles, labels and legends. * * @return A chart corresponding to the specification in the supplied * parameters./* ww w . j av a 2 s . c o m*/ */ public static JFreeChart buildChart(Map params, Font font) { if (params == null) { throw new IllegalArgumentException("Null 'params' argument."); } JFreeChart chart = null; // *** CHART TYPE ** String[] chartType = (String[]) params.get("cht"); int dataType = -1; // 0 = PieDataset; 1 = XYDataset; 2 = special // pie charts: 'p' and 'p3' if (chartType[0].equals("p")) { chart = createPieChart(); dataType = 0; } else if (chartType[0].equals("p3")) { chart = createPieChart3D(); dataType = 0; } // line chart: 'lc' else if (chartType[0].equals("lc")) { chart = createLineChart(); dataType = 1; } // sparkline: 'ls' else if (chartType[0].equals("ls")) { chart = createSparklineChart(); dataType = 1; } // xy chart: 'lxy' else if (chartType[0].equals("lxy")) { chart = createLineChart(); dataType = 3; } // bar charts: 'bhs', 'bhg', 'bhs' and 'bhg' else if (chartType[0].equals("bhs")) { chart = createStackedBarChart(PlotOrientation.HORIZONTAL); dataType = 2; } else if (chartType[0].equals("bhg")) { chart = createBarChart(PlotOrientation.HORIZONTAL); dataType = 2; } else if (chartType[0].equals("bvs")) { chart = createStackedBarChart(PlotOrientation.VERTICAL); dataType = 2; } else if (chartType[0].equals("bvg")) { chart = createBarChart(PlotOrientation.VERTICAL); dataType = 2; } else if (chartType[0].equals("bhs3")) { chart = createStackedBarChart3D(PlotOrientation.HORIZONTAL); dataType = 2; } else if (chartType[0].equals("bhg3")) { chart = createBarChart3D(PlotOrientation.HORIZONTAL); dataType = 2; } else if (chartType[0].equals("bvs3")) { chart = createStackedBarChart3D(PlotOrientation.VERTICAL); dataType = 2; } else if (chartType[0].equals("bvg3")) { chart = createBarChart3D(PlotOrientation.VERTICAL); dataType = 2; } // scatter chart: 's' else if (chartType[0].equals("s")) { chart = createScatterChart(); dataType = 4; } else if (chartType[0].equals("v")) { throw new RuntimeException("Venn diagrams not implemented."); // TODO: fix this. } else { throw new RuntimeException("Unknown chart type: " + chartType[0]); } chart.getPlot().setOutlineVisible(false); // *** CHART AXES *** List axes = new java.util.ArrayList(); String[] axisStr = (String[]) params.get("chxt"); if (axisStr != null) { if (chart.getPlot() instanceof XYPlot) { XYPlot plot = (XYPlot) chart.getPlot(); processAxisStr(plot, axisStr[0], axes); } else if (chart.getPlot() instanceof CategoryPlot) { CategoryPlot plot = (CategoryPlot) chart.getPlot(); if (plot.getOrientation() == PlotOrientation.VERTICAL) { processAxisStrV(plot, axisStr[0], axes); } else { processAxisStrH(plot, axisStr[0], axes); } } } // *** AXIS RANGES *** String[] axisRangeStr = (String[]) params.get("chxr"); if (axisRangeStr != null) { String[] ranges = breakString(axisRangeStr[0], '|'); for (int i = 0; i < ranges.length; i++) { int comma1 = ranges[i].indexOf(','); int comma2 = ranges[i].indexOf(',', comma1 + 1); int axisIndex = Integer.parseInt(ranges[i].substring(0, comma1)); float lowerBound = Float.parseFloat(ranges[i].substring(comma1 + 1, comma2)); float upperBound = Float.parseFloat(ranges[i].substring(comma2 + 1)); Axis axis = (Axis) axes.get(axisIndex); if (axis instanceof GValueAxis) { GValueAxis gaxis = (GValueAxis) axis; gaxis.setLabelAxisStart(lowerBound); gaxis.setLabelAxisEnd(upperBound); } } } // *** AXIS LABELS *** String[] axisLabelStr = (String[]) params.get("chxl"); if (axisLabelStr != null) { Pattern p = Pattern.compile("\\d+:\\|"); Matcher m = p.matcher(axisLabelStr[0]); if (m.find()) { int keyStart = m.start(); int labelStart = m.end(); while (m.find(labelStart)) { String keyStr = axisLabelStr[0].substring(keyStart, labelStart - 2); int axisIndex = Integer.parseInt(keyStr); keyStart = m.start(); String labelStr = axisLabelStr[0].substring(labelStart, keyStart - 1); String[] labels = breakString(labelStr, '|'); GLabelledAxis axis = (GLabelledAxis) axes.get(axisIndex); axis.setTickLabels(Arrays.asList(labels)); labelStart = m.end(); } // process the final item String keyStr = axisLabelStr[0].substring(keyStart, labelStart - 2); String labelStr = axisLabelStr[0].substring(labelStart); int axisIndex = Integer.parseInt(keyStr); if (labelStr.endsWith("|")) { labelStr = labelStr.substring(0, labelStr.length() - 1); } String[] labels = breakString(labelStr, '|'); GLabelledAxis axis = (GLabelledAxis) axes.get(axisIndex); axis.setTickLabels(Arrays.asList(labels)); } else { throw new RuntimeException("No matching pattern!"); } } // ** EXPLICIT AXIS LABEL POSITIONS String[] axisPositionStr = (String[]) params.get("chxp"); if (axisPositionStr != null) { String[] positions = breakString(axisPositionStr[0], '|'); for (int i = 0; i < positions.length; i++) { int c1 = positions[i].indexOf(','); int axisIndex = Integer.parseInt(positions[i].substring(0, c1)); String remainingStr = positions[i].substring(c1 + 1); String[] valueStr = breakString(remainingStr, ','); List tickValues = new java.util.ArrayList(valueStr.length); Axis axis = (Axis) axes.get(axisIndex); if (axis instanceof GValueAxis) { GValueAxis gaxis = (GValueAxis) axes.get(axisIndex); for (int j = 0; j < valueStr.length; j++) { float pos = Float.parseFloat(valueStr[j]); tickValues.add(new Float(pos)); } gaxis.setTickLabelPositions(tickValues); } // FIXME: what about a CategoryAxis? } } // *** CHART TITLE *** String[] titleStr = (String[]) params.get("chtt"); if (titleStr != null) { // process the title String[] s = breakString(titleStr[0], '|'); for (int i = 0; i < s.length; i++) { TextTitle t = new TextTitle(s[i].replace('+', ' ')); t.setPaint(Color.darkGray); // Google seems to use 14pt fonts for titles and 12pt fonts for // all other text. Make sure this relationship remains. t.setFont(font.deriveFont(font.getSize2D() * 14f / 12f)); chart.addSubtitle(t); } // and the font and colour String[] fontStr = (String[]) params.get("chts"); if (fontStr != null) { int c1 = fontStr[0].indexOf(','); String colorStr = null; String fontSizeStr = null; if (c1 != -1) { colorStr = fontStr[0].substring(0, c1); fontSizeStr = fontStr[0].substring(c1 + 1); } else { colorStr = fontStr[0]; } Color color = parseColor(colorStr); int size = 12; if (fontSizeStr != null) { size = Integer.parseInt(fontSizeStr); } for (int i = 0; i < chart.getSubtitleCount(); i++) { Title t = chart.getSubtitle(i); if (t instanceof TextTitle) { TextTitle tt = (TextTitle) t; tt.setPaint(color); tt.setFont(font.deriveFont((float) size)); } } } } // *** CHART DATA *** String[] dataStr = (String[]) params.get("chd"); String scalingStr = null; if (dataStr.length > 0 && dataStr[0].startsWith("t:")) { // Only look at chds when text encoding is used String[] chds = (String[]) params.get("chds"); if (chds != null && chds.length > 0) { scalingStr = chds[0]; } } // we'll also process an optional second dataset that is provided as // an Eastwood extension...this isn't part of the Google Chart API String[] d2Str = (String[]) params.get("ewd2"); // 'p' and 'p3' - create PieDataset if (dataType == 0) { PieDataset dataset = DataUtilities.parsePieDataset(dataStr[0], scalingStr); PiePlot plot = (PiePlot) chart.getPlot(); plot.setDataset(dataset); // ignore d2Str as there is currently no need for a second pie // dataset. } // 'lc' - create XYDataset else if (dataType == 1) { XYPlot plot = (XYPlot) chart.getPlot(); XYDataset dataset = DataUtilities.parseXYDataset(dataStr[0], scalingStr); plot.setDataset(dataset); if (d2Str != null) { // an Eastwood extension XYDataset d2 = DataUtilities.parseXYDataset(d2Str[0], scalingStr); plot.setDataset(1, d2); } } // 'bhs', 'bhg', 'bvs', 'bvg' else if (dataType == 2) { CategoryPlot plot = (CategoryPlot) chart.getPlot(); CategoryDataset dataset = DataUtilities.parseCategoryDataset(dataStr[0], scalingStr); plot.setDataset(dataset); if (d2Str != null) { // an Eastwood extension CategoryDataset d2 = DataUtilities.parseCategoryDataset(d2Str[0], scalingStr); plot.setDataset(1, d2); } } // 'lxy' else if (dataType == 3) { XYPlot plot = (XYPlot) chart.getPlot(); XYDataset dataset = DataUtilities.parseXYDataset2(dataStr[0], scalingStr); plot.setDataset(dataset); if (d2Str != null) { // an Eastwood extension XYDataset d2 = DataUtilities.parseXYDataset2(d2Str[0], scalingStr); plot.setDataset(1, d2); } } else if (dataType == 4) { XYPlot plot = (XYPlot) chart.getPlot(); XYSeriesCollection dataset = DataUtilities.parseScatterDataset(dataStr[0], scalingStr); if (dataset.getSeriesCount() > 1) { dataset.removeSeries(1); } plot.setDataset(dataset); if (d2Str != null) { // an Eastwood extension XYDataset d2 = DataUtilities.parseXYDataset2(d2Str[0], scalingStr); plot.setDataset(1, d2); } } if (chart.getPlot() instanceof XYPlot) { XYPlot plot = (XYPlot) chart.getPlot(); plot.getDomainAxis().setLabelFont(font); plot.getDomainAxis().setTickLabelFont(font); plot.getRangeAxis().setLabelFont(font); plot.getRangeAxis().setTickLabelFont(font); } else if (chart.getPlot() instanceof CategoryPlot) { CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.getDomainAxis().setLabelFont(font); plot.getDomainAxis().setTickLabelFont(font); plot.getRangeAxis().setLabelFont(font); plot.getRangeAxis().setTickLabelFont(font); } // *** CHART COLOURS *** String[] colorStr = (String[]) params.get("chco"); if (colorStr != null) { Color[] colors = parseColors(colorStr[0]); if (dataType == 0) { PiePlot plot = (PiePlot) chart.getPlot(); applyColorsToPiePlot(plot, colors); } else { AbstractRenderer renderer = null; if (chart.getPlot() instanceof CategoryPlot) { CategoryPlot plot = (CategoryPlot) chart.getPlot(); renderer = (AbstractRenderer) plot.getRenderer(); renderer.setBasePaint(colors[0]); } else if (chart.getPlot() instanceof XYPlot) { XYPlot plot = (XYPlot) chart.getPlot(); renderer = (AbstractRenderer) plot.getRenderer(); renderer.setBasePaint(colors[colors.length - 1]); } for (int i = 0; i < colors.length; i++) { renderer.setSeriesPaint(i, colors[i]); } } } else { Plot plot = chart.getPlot(); if (plot instanceof PiePlot) { applyColorsToPiePlot((PiePlot) chart.getPlot(), new Color[] { new Color(255, 153, 0) }); } } // *** CHART LINE STYLES *** String[] lineStr = (String[]) params.get("chls"); if (lineStr != null && chart.getPlot() instanceof XYPlot) { Stroke[] strokes = parseLineStyles(lineStr[0]); XYPlot plot = (XYPlot) chart.getPlot(); XYItemRenderer renderer = plot.getRenderer(); for (int i = 0; i < strokes.length; i++) { renderer.setSeriesStroke(i, strokes[i]); } renderer.setBaseStroke(strokes[strokes.length - 1]); } // *** CHART GRID LINES if (dataType != 0) { String[] gridStr = (String[]) params.get("chg"); if (gridStr != null) { processGridLinesSpec(gridStr[0], chart); } } // *** CHART LABELS if (dataType == 0) { // pie chart String[] labelStr = (String[]) params.get("chl"); if (labelStr != null) { String[] s = breakString(labelStr[0], '|'); List labels = Arrays.asList(s); PiePlot plot = (PiePlot) chart.getPlot(); if (labels.size() > 0) { plot.setLabelGenerator(new GPieSectionLabelGenerator(labels)); plot.setLabelFont(font); plot.setLabelPaint(Color.darkGray); } } } String[] legendStr = (String[]) params.get("chdl"); if (legendStr != null) { // process the title String[] s = breakString(legendStr[0], '|'); List labels = Arrays.asList(s); if (labels.size() > 0) { Plot p = chart.getPlot(); if (p instanceof CategoryPlot) { CategoryPlot plot = (CategoryPlot) chart.getPlot(); BarRenderer renderer = (BarRenderer) plot.getRenderer(); renderer.setLegendItemLabelGenerator(new GSeriesLabelGenerator(labels)); renderer.setBaseSeriesVisibleInLegend(false); for (int i = 0; i < labels.size(); i++) { renderer.setSeriesVisibleInLegend(i, Boolean.TRUE); } } else if (p instanceof XYPlot) { XYPlot plot = (XYPlot) chart.getPlot(); XYItemRenderer renderer = plot.getRenderer(); renderer.setLegendItemLabelGenerator(new GSeriesLabelGenerator(labels)); renderer.setBaseSeriesVisibleInLegend(false); for (int i = 0; i < labels.size(); i++) { renderer.setSeriesVisibleInLegend(i, Boolean.TRUE); } } else if (p instanceof PiePlot) { PiePlot plot = (PiePlot) chart.getPlot(); plot.setLegendLabelGenerator(new GPieSectionLabelGenerator(labels)); } LegendTitle legend = new LegendTitle(chart.getPlot()); RectangleEdge pos = RectangleEdge.RIGHT; String[] chdlp = (String[]) params.get("chdlp"); if (chdlp != null) { if ("b".equals(chdlp[0])) { pos = RectangleEdge.BOTTOM; } else if ("t".equals(chdlp[0])) { pos = RectangleEdge.TOP; } else if ("l".equals(chdlp[0])) { pos = RectangleEdge.LEFT; } } legend.setPosition(pos); legend.setItemFont(font); legend.setItemPaint(Color.darkGray); chart.addSubtitle(legend); } } // *** CHART MARKERS *** String[] markerStr = (String[]) params.get("chm"); if (markerStr != null) { String[] markers = breakString(markerStr[0], '|'); for (int i = 0; i < markers.length; i++) { addMarker(markers[i], chart); } } // *** CHART FILL ***/ String[] fillStr = (String[]) params.get("chf"); if (fillStr != null) { // process the 1 or 2 fill specs int i = fillStr[0].indexOf('|'); if (i == -1) { processFillSpec(fillStr[0], chart); } else { String fs1 = fillStr[0].substring(0, i); String fs2 = fillStr[0].substring(i + 1); processFillSpec(fs1, chart); processFillSpec(fs2, chart); } } // process the 'ewtr' tag, if present processEWTR(params, chart); return chart; }
From source file:org.pentaho.plugin.jfreereport.reportcharts.AbstractChartExpression.java
protected void configureChart(final JFreeChart chart) { // Misc Properties final TextTitle chartTitle = chart.getTitle(); if (chartTitle != null) { final Font titleFont = Font.decode(getTitleFont()); chartTitle.setFont(titleFont); }//from www .jav a 2s .co m if (isAntiAlias() == false) { chart.setAntiAlias(false); } chart.setBorderVisible(isShowBorder()); final Color backgroundColor = parseColorFromString(getBackgroundColor()); if (backgroundColor != null) { chart.setBackgroundPaint(backgroundColor); } if (plotBackgroundColor != null) { chart.getPlot().setBackgroundPaint(plotBackgroundColor); } chart.getPlot().setBackgroundAlpha(plotBackgroundAlpha); chart.getPlot().setForegroundAlpha(plotForegroundAlpha); final Color borderCol = parseColorFromString(getBorderColor()); if (borderCol != null) { chart.setBorderPaint(borderCol); } //remove legend if showLegend = false if (!isShowLegend()) { chart.removeLegend(); } else { //if true format legend final LegendTitle chLegend = chart.getLegend(); if (chLegend != null) { final RectangleEdge loc = translateEdge(legendLocation.toLowerCase()); if (loc != null) { chLegend.setPosition(loc); } if (getLegendFont() != null) { chLegend.setItemFont(Font.decode(getLegendFont())); } if (!isDrawLegendBorder()) { chLegend.setBorder(BlockBorder.NONE); } if (legendBackgroundColor != null) { chLegend.setBackgroundPaint(legendBackgroundColor); } if (legendTextColor != null) { chLegend.setItemPaint(legendTextColor); } } } final Plot plot = chart.getPlot(); plot.setNoDataMessageFont(Font.decode(getLabelFont())); final String message = getNoDataMessage(); if (message != null) { plot.setNoDataMessage(message); } plot.setOutlineVisible(isChartSectionOutline()); if (backgroundImage != null) { if (plotImageCache != null) { plot.setBackgroundImage(plotImageCache); } else { final ExpressionRuntime expressionRuntime = getRuntime(); final ProcessingContext context = expressionRuntime.getProcessingContext(); final ResourceKey contentBase = context.getContentBase(); final ResourceManager manager = context.getResourceManager(); try { final ResourceKey key = createKeyFromString(manager, contentBase, backgroundImage); final Resource resource = manager.create(key, null, Image.class); final Image image = (Image) resource.getResource(); plot.setBackgroundImage(image); plotImageCache = image; } catch (Exception e) { logger.error("ABSTRACTCHARTEXPRESSION.ERROR_0007_ERROR_RETRIEVING_PLOT_IMAGE", e); //$NON-NLS-1$ throw new IllegalStateException("Failed to process chart"); } } } }
From source file:org.pentaho.chart.plugin.jfreechart.JFreeChartFactoryEngine.java
protected void initChart(JFreeChart chart, ChartModel chartModel) { if (chartModel.getBackground() instanceof Integer) { chart.setBackgroundPaint(new Color(0x00FFFFFF & (Integer) chartModel.getBackground())); } else {/* w w w.java2 s .c o m*/ chart.setBackgroundPaint(Color.WHITE); } if ((chartModel.getTitle() != null) && (chartModel.getTitle().getText() != null) && (chartModel.getTitle().getText().trim().length() > 0)) { Font font = ChartUtils.getFont(chartModel.getTitle().getFontFamily(), chartModel.getTitle().getFontStyle(), chartModel.getTitle().getFontWeight(), chartModel.getTitle().getFontSize()); if (font != null) { chart.getTitle().setFont(font); } RectangleEdge rectangleEdge = RectangleEdge.TOP; if (chartModel.getTitle().getLocation() != null) { switch (chartModel.getTitle().getLocation()) { case RIGHT: rectangleEdge = RectangleEdge.BOTTOM; break; case LEFT: rectangleEdge = RectangleEdge.LEFT; break; case BOTTOM: rectangleEdge = RectangleEdge.BOTTOM; break; } } chart.getTitle().setPosition(rectangleEdge); if (RectangleEdge.isTopOrBottom(rectangleEdge)) { HorizontalAlignment horizontalAlignment = HorizontalAlignment.CENTER; if (chartModel.getTitle().getAlignment() != null) { switch (chartModel.getTitle().getAlignment()) { case LEFT: horizontalAlignment = horizontalAlignment.LEFT; break; case RIGHT: horizontalAlignment = horizontalAlignment.RIGHT; break; } } chart.getTitle().setHorizontalAlignment(horizontalAlignment); } } if ((chartModel.getLegend() != null) && chartModel.getLegend().getVisible()) { Font font = ChartUtils.getFont(chartModel.getLegend().getFontFamily(), chartModel.getLegend().getFontStyle(), chartModel.getLegend().getFontWeight(), chartModel.getLegend().getFontSize()); if (font != null) { chart.getLegend().setItemFont(font); } if (!chartModel.getLegend().getBorderVisible()) { chart.getLegend().setFrame(BlockBorder.NONE); } } chart.setBorderVisible(chartModel.getBorderVisible()); if (chartModel.getBorderColor() instanceof Integer) { chart.setBorderPaint(new Color(0x00FFFFFF & (Integer) chartModel.getBorderColor())); } for (StyledText subtitle : chartModel.getSubtitles()) { if ((subtitle.getText()) != null && (subtitle.getText().trim().length() > 0)) { TextTitle textTitle = new TextTitle(subtitle.getText()); Font font = ChartUtils.getFont(subtitle.getFontFamily(), subtitle.getFontStyle(), subtitle.getFontWeight(), subtitle.getFontSize()); if (font != null) { textTitle.setFont(font); } if (subtitle.getColor() != null) { textTitle.setPaint(new Color(0x00FFFFFF & subtitle.getColor())); } if (subtitle.getBackgroundColor() != null) { textTitle.setBackgroundPaint(new Color(0x00FFFFFF & subtitle.getBackgroundColor())); } chart.addSubtitle(textTitle); } } }