List of usage examples for org.jfree.chart.renderer.xy XYLineAndShapeRenderer setShapesVisible
public void setShapesVisible(boolean visible)
From source file:org.jgrasstools.gears.ui.OmsMatrixCharter.java
@SuppressWarnings("deprecation") private JFreeChart doLineChart() { XYSeriesCollection collection = getSeriesCollection(); PlotOrientation orientation = PlotOrientation.VERTICAL; if (doHorizontal) { orientation = PlotOrientation.HORIZONTAL; }/*w ww .j a v a2 s .c om*/ JFreeChart chart = ChartFactory.createXYLineChart(inTitle, inLabels[0], inLabels[1], collection, orientation, doLegend, true, false); XYPlot plot = (XYPlot) chart.getPlot(); // plot.setDomainGridlinePaint(Color.red); // plot.setRangeGridlinePaint(Color.cyan); // plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); XYItemRenderer plotRenderer = plot.getRenderer(); if (plotRenderer instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plotRenderer; if (doPoints) { renderer.setShapesVisible(true); renderer.setShapesFilled(true); } if (inColors != null) { String[] colorSplit = inColors.split(";"); for (int i = 0; i < colorSplit.length; i++) { String[] split = colorSplit[i].split(","); int r = (int) Double.parseDouble(split[0]); int g = (int) Double.parseDouble(split[1]); int b = (int) Double.parseDouble(split[2]); renderer.setSeriesPaint(i, new Color(r, g, b)); } } } NumberAxis yAxis = (NumberAxis) plot.getRangeAxis(); yAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits()); double delta = (max - min) * 0.1; yAxis.setRange(min, max + delta); yAxis.setMinorTickCount(4); yAxis.setMinorTickMarksVisible(true); if (inFormats != null && inFormats.length > 1 && inFormats[1].trim().length() > 0) { yAxis.setNumberFormatOverride(new DecimalFormat(inFormats[1])); } if (inFormats != null && inFormats.length > 0 && inFormats[0].trim().length() > 0) { ValueAxis domainAxis = plot.getDomainAxis(); if (domainAxis instanceof NumberAxis) { NumberAxis xAxis = (NumberAxis) domainAxis; xAxis.setNumberFormatOverride(new DecimalFormat(inFormats[0])); } } return chart; }
From source file:com.freedomotic.jfrontend.extras.GraphPanel.java
private void createChart(UsageDataFrame points, String title) { series = new TimeSeries(title); for (UsageData d : points.getData()) { Date resultdate = d.getDateTime(); Millisecond ms_read = new Millisecond(resultdate); int poweredValue = -1; if (d.getObjBehavior().equalsIgnoreCase("powered")) { poweredValue = d.getObjValue().equalsIgnoreCase("true") ? 1 : 0; } else if (d.getObjBehavior().equalsIgnoreCase("brigthness")) { try { poweredValue = Integer.parseInt(d.getObjValue()); } catch (NumberFormatException ex) { poweredValue = -1;// w ww . java2s . c o m } } series.addOrUpdate(ms_read, poweredValue); } XYDataset xyDataset = new TimeSeriesCollection(series); chart = ChartFactory.createTimeSeriesChart("Chart", "TIME", "VALUE", xyDataset, true, // legend true, // tooltips false // urls ); chart.setAntiAlias(true); // Set plot styles XYPlot plot = (XYPlot) chart.getPlot(); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(2.0, 2.0, 2.0, 2.0)); // Set series line styles plot.setRenderer(new XYStepRenderer()); XYItemRenderer r = plot.getRenderer(); if (r instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r; renderer.setShapesVisible(true); renderer.setShapesFilled(true); } // Set date axis style DateAxis axis = (DateAxis) plot.getDomainAxis(); String formatString = "MM-dd HH"; DateTickUnitType dtut = DateTickUnitType.HOUR; if (jComboGranularity.getSelectedItem().equals("Year")) { formatString = "yyyy"; dtut = DateTickUnitType.YEAR; } else if (jComboGranularity.getSelectedItem().equals("Month")) { axis.setDateFormatOverride(new SimpleDateFormat("yyyy-MM")); dtut = DateTickUnitType.MONTH; } else if (jComboGranularity.getSelectedItem().equals("Day")) { axis.setDateFormatOverride(new SimpleDateFormat("MM-dd")); dtut = DateTickUnitType.DAY; } else if (jComboGranularity.getSelectedItem().equals("Minute")) { formatString = "MM-dd HH:mm"; dtut = DateTickUnitType.MINUTE; } else if (jComboGranularity.getSelectedItem().equals("Second")) { formatString = "HH:mm:SS"; dtut = DateTickUnitType.SECOND; } DateFormat formatter = new SimpleDateFormat(formatString); DateTickUnit unit = new DateTickUnit(dtut, 1, formatter); axis.setTickUnit(unit); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(800, 500)); graphPanel.removeAll(); graphPanel.add(chartPanel); }
From source file:charts.Chart.java
public static void MultipleLineChart(XYSeriesCollection datasets, String title, String x_axis_label, String y_axis_label) {/*ww w.j a va 2 s .co m*/ JFrame chartwindow = new JFrame(title); JFreeChart jfreechart = ChartFactory.createXYLineChart(title, x_axis_label, y_axis_label, datasets, PlotOrientation.VERTICAL, true, true, true); XYPlot xyplot = (XYPlot) jfreechart.getPlot(); xyplot.setBackgroundPaint(Color.white); xyplot.setRangeGridlinePaint(Color.black); NumberAxis rangeAxis = (NumberAxis) xyplot.getRangeAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); rangeAxis.setAutoRangeIncludesZero(true); XYLineAndShapeRenderer lineandshaperenderer = (XYLineAndShapeRenderer) xyplot.getRenderer(); lineandshaperenderer.setShapesVisible(true); lineandshaperenderer.setDrawOutlines(true); lineandshaperenderer.setUseFillPaint(true); lineandshaperenderer.setFillPaint(Color.white); JPanel jpanel = new ChartPanel(jfreechart); jpanel.setPreferredSize(new Dimension(defaultwidth, defaultheight)); chartwindow.setContentPane(jpanel); chartwindow.pack(); RefineryUtilities.centerFrameOnScreen(chartwindow); chartwindow.setVisible(true); }
From source file:com.google.gwt.benchmarks.viewer.server.ReportImageServer.java
private void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException { String uri = request.getRequestURI(); String requestString = uri.split("test_images/")[1]; String[] requestParams = requestString.split("/"); String reportName = URLDecoder.decode(requestParams[0], charset); String categoryName = URLDecoder.decode(requestParams[1], charset); // String className = URLDecoder.decode(requestParams[2], charset); String testName = URLDecoder.decode(requestParams[3], charset); String agent = URLDecoder.decode(requestParams[4], charset); ReportDatabase db = ReportDatabase.getInstance(); Report report = db.getReport(reportName); List<Category> categories = report.getCategories(); Category category = getCategoryByName(categories, categoryName); List<Benchmark> benchmarks = category.getBenchmarks(); Benchmark benchmark = getBenchmarkByName(benchmarks, testName); List<Result> results = benchmark.getResults(); Result result = getResultsByAgent(results, agent); String title = BrowserInfo.getBrowser(agent); JFreeChart chart = createChart(testName, result, title, results); chart.getTitle().setFont(Font.decode("Verdana BOLD 12")); chart.setAntiAlias(true);//from ww w.jav a2s. c o m chart.setBorderVisible(true); chart.setBackgroundPaint(new Color(241, 241, 241)); Plot plot = chart.getPlot(); plot.setDrawingSupplier(getDrawingSupplier()); plot.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 640, 480, new Color(200, 200, 200))); if (plot instanceof XYPlot) { XYPlot xyplot = (XYPlot) plot; Font labelFont = Font.decode("Verdana PLAIN"); xyplot.getDomainAxis().setLabelFont(labelFont); xyplot.getRangeAxis().setLabelFont(labelFont); org.jfree.chart.renderer.xy.XYItemRenderer xyitemrenderer = xyplot.getRenderer(); xyitemrenderer.setStroke(new BasicStroke(4)); if (xyitemrenderer instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer) xyitemrenderer; xylineandshaperenderer.setShapesVisible(true); xylineandshaperenderer.setShapesFilled(true); } } // Try to fit all the graphs into a 1024 window, with a min of 240 and a max // of 480 final int graphWidth = Math.max(240, Math.min(480, (1024 - 10 * results.size()) / results.size())); BufferedImage img = chart.createBufferedImage(graphWidth, 240); byte[] image = EncoderUtil.encode(img, ImageFormat.PNG); // The images have unique URLs; might as well set them to never expire. response.setHeader("Cache-Control", "max-age=0"); response.setHeader("Expires", "Fri, 2 Jan 1970 00:00:00 GMT"); response.setContentType("image/png"); response.setContentLength(image.length); OutputStream output = response.getOutputStream(); output.write(image); }
From source file:org.pentaho.plugin.jfreereport.reportcharts.XYAreaLineChartExpression.java
protected void configureChart(final JFreeChart chart) { super.configureChart(chart); final XYPlot plot = chart.getXYPlot(); if (isSharedRangeAxis() == false) { final ValueAxis linesAxis = plot.getRangeAxis(1); if (linesAxis instanceof NumberAxis) { final NumberAxis numberAxis = (NumberAxis) linesAxis; numberAxis.setAutoRangeIncludesZero(isLineAxisIncludesZero()); numberAxis.setAutoRangeStickyZero(isLineAxisStickyZero()); if (getLinePeriodCount() > 0) { if (getLineTicksLabelFormat() != null) { final FastDecimalFormat formatter = new FastDecimalFormat(getLineTicksLabelFormat(), getResourceBundleFactory().getLocale()); numberAxis.setTickUnit(new FastNumberTickUnit(getLinePeriodCount(), formatter)); } else { numberAxis.setTickUnit(new FastNumberTickUnit(getLinePeriodCount())); }//from ww w.j av a 2s. com } else { if (getLineTicksLabelFormat() != null) { final DecimalFormat formatter = new DecimalFormat(getLineTicksLabelFormat(), new DecimalFormatSymbols(getResourceBundleFactory().getLocale())); numberAxis.setNumberFormatOverride(formatter); } } } else if (linesAxis instanceof DateAxis) { final DateAxis numberAxis = (DateAxis) linesAxis; if (getLinePeriodCount() > 0 && getLineTimePeriod() != null) { if (getLineTicksLabelFormat() != null) { final SimpleDateFormat formatter = new SimpleDateFormat(getLineTicksLabelFormat(), new DateFormatSymbols(getResourceBundleFactory().getLocale())); numberAxis.setTickUnit(new DateTickUnit(getDateUnitAsInt(getLineTimePeriod()), (int) getLinePeriodCount(), formatter)); } else { numberAxis.setTickUnit(new DateTickUnit(getDateUnitAsInt(getLineTimePeriod()), (int) getLinePeriodCount())); } } else if (getRangeTickFormatString() != null) { final SimpleDateFormat formatter = new SimpleDateFormat(getRangeTickFormatString(), new DateFormatSymbols(getResourceBundleFactory().getLocale())); numberAxis.setDateFormatOverride(formatter); } } if (linesAxis != null) { final Font labelFont = Font.decode(getLabelFont()); linesAxis.setLabelFont(labelFont); linesAxis.setTickLabelFont(labelFont); if (getLineTitleFont() != null) { linesAxis.setLabelFont(getLineTitleFont()); } if (getLineTickFont() != null) { linesAxis.setTickLabelFont(getLineTickFont()); } final int level = getRuntime().getProcessingContext().getCompatibilityLevel(); if (ClassicEngineBoot.isEnforceCompatibilityFor(level, 3, 8)) { final double lineRangeMinimumVal = lineRangeMinimum == null ? 0 : lineRangeMinimum; final double lineRangeMaximumVal = lineRangeMaximum == null ? 0 : lineRangeMaximum; if (lineRangeMinimum != null) { linesAxis.setLowerBound(getLineRangeMinimum()); } if (lineRangeMaximum != null) { linesAxis.setUpperBound(getRangeMaximum()); } if (lineRangeMinimumVal == 0 && lineRangeMaximumVal == 1) { linesAxis.setLowerBound(0); linesAxis.setUpperBound(1); linesAxis.setAutoRange(true); } } else { if (lineRangeMinimum != null) { linesAxis.setLowerBound(lineRangeMinimum); } if (lineRangeMaximum != null) { linesAxis.setUpperBound(lineRangeMaximum); } linesAxis.setAutoRange(isLineAxisAutoRange()); } } } final XYLineAndShapeRenderer linesRenderer = (XYLineAndShapeRenderer) plot.getRenderer(1); if (linesRenderer != null) { //set stroke with line width linesRenderer.setStroke(translateLineStyle(getLineWidth(), getLineStyle())); //hide shapes on line linesRenderer.setShapesVisible(isMarkersVisible()); linesRenderer.setBaseShapesFilled(isMarkersVisible()); //set colors for each line for (int i = 0; i < lineSeriesColor.size(); i++) { final String s = (String) lineSeriesColor.get(i); linesRenderer.setSeriesPaint(i, parseColorFromString(s)); } } }
From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.GOESChartUIComponent.java
/*********************************************************************************************** * Customise the XYPlot of a new chart, e.g. for fixed range axes. * * @param datasettype/*from w w w . ja v a 2 s . co m*/ * @param primarydataset * @param secondarydatasets * @param updatetype * @param displaylimit * @param channelselector * @param debug * * @return JFreeChart */ public JFreeChart createCustomisedChart(final DatasetType datasettype, final XYDataset primarydataset, final List<XYDataset> secondarydatasets, final DataUpdateType updatetype, final int displaylimit, final ChannelSelectorUIComponentInterface channelselector, final boolean debug) { final JFreeChart jFreeChart; // A plain Chart is an XYPlot // with a DateAxis for the x-axis (index 0) and a NumberAxis for the y-axis (index 0). // The default renderer is an XYLineAndShapeRenderer jFreeChart = ChartHelper.createChart(primarydataset, ObservatoryInstrumentHelper.getCurrentObservatoryTimeZone(REGISTRY.getFramework(), getDAO(), debug), getMetadata(), getChannelCount(), hasTemperatureChannel(), updatetype, displaylimit, channelselector, debug); // Customise the Chart for GOES data // Channels 0 & 1 are Data on a LogarithmicAxis, // Channel 2 is Ratio on a NumberAxis if (jFreeChart != null) { final String strLabelFlux; final String strLabelRatio; final XYPlot plot; final LogarithmicAxis axisFlux; final DateAxis axisDate; // The set of Metadata available should include the Instrument // and any items from the current observation strLabelFlux = MetadataHelper.getMetadataValueByKey(getMetadata(), MetadataDictionary.KEY_OBSERVATION_AXIS_LABEL_Y.getKey() + MetadataDictionary.SUFFIX_SERIES_ZERO); strLabelRatio = MetadataHelper.getMetadataValueByKey(getMetadata(), MetadataDictionary.KEY_OBSERVATION_AXIS_LABEL_Y.getKey() + MetadataDictionary.SUFFIX_SERIES_ONE); plot = jFreeChart.getXYPlot(); //---------------------------------------------------------------------------------- // Replace the RangeAxis at index 0 NumberAxis with a LogarithmicAxis // The RangeAxis at index 0 is the LogarithmicAxis, to be used by Channels 0 & 1 (Data) axisFlux = new LogarithmicAxis(strLabelFlux); axisFlux.setRange(1.0E-09, 1.0E-02); axisFlux.setAllowNegativesFlag(false); axisFlux.setLog10TickLabelsFlag(true); plot.setRangeAxis(0, axisFlux); // Map the dataset to the axis plot.setDataset(INDEX_FLUX, primarydataset); plot.mapDatasetToRangeAxis(0, 0); plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_LEFT); //---------------------------------------------------------------------------------- // Customise the DomainAxis at index 0 axisDate = (DateAxis) plot.getDomainAxis(); // Showing the YYYY-MM-DD makes a very long label... // ToDo Consider ThreadLocal axisDate.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss")); // Now customise the Flux renderer to improve legend visibility // Use the same colours as on http://www.swpc.noaa.gov/ // blue=0.5 - 4.0A red=1.0 - 8.0A ChartUIHelper.customisePlotRenderer(plot, INDEX_FLUX); //---------------------------------------------------------------------------------- // Set the RangeAxis at index 1 to a new NumberAxis, to be used by Channel 2 (Ratio) if ((secondarydatasets != null) && (secondarydatasets.size() == 1)) { final NumberAxis axisRatio; final XYLineAndShapeRenderer rendererRatio; axisRatio = new NumberAxis(strLabelRatio); plot.setRangeAxis(1, axisRatio); // The RangeAxis at index 1 is the NumberAxis, to be used by Channel 2 plot.setDataset(INDEX_RATIO, secondarydatasets.get(0)); plot.mapDatasetToRangeAxis(1, 1); plot.setRangeAxisLocation(1, AxisLocation.TOP_OR_RIGHT); rendererRatio = new XYLineAndShapeRenderer(); rendererRatio.setLinesVisible(true); rendererRatio.setShapesVisible(false); // Channel 2 is Ratio rendererRatio.setSeriesPaint(0, ChartUIHelper.getStandardColour(2).getColor()); rendererRatio.setLegendLine(SHAPE_LEGEND); plot.setRenderer(INDEX_RATIO, rendererRatio); //ChartHelper.customisePlotRenderer(plot, INDEX_RATIO); } } return (jFreeChart); }
From source file:com.zigabyte.stock.stratplot.StrategyPlotter.java
/** Build combined chart containing the account cash/stocks/total values chart over dates on bottom and the percentage change over dates chart on top. // w w w . j ava2 s . com @return y-axes that need to be re-ranged when data changes. **/ private NumberAxis[] plotAccountHistory(XYDataset accountData, String title, Date startDate, Date endDate) { final DateAxis dateAxis = new DateAxis(); dateAxis.setRange(startDate, endDate); final NumberAxis percentAxis = new NumberAxis("% change"); percentAxis.setAutoRangeIncludesZero(false); final NumberAxis priceAxis = new NumberAxis("US$"); priceAxis.setAutoRangeIncludesZero(true); boolean useShapes = // use shapes if 3 months or less (endDate.getTime() - startDate.getTime() < 93 * 24 * 60 * 60 * 1000L); XYLineAndShapeRenderer accountRenderer = new XYLineAndShapeRenderer(); accountRenderer.setShapesVisible(useShapes); XYPlot accountPlot = new XYPlot(accountData, dateAxis, priceAxis, accountRenderer); // compare only total percent data to zoom in on its fluctuations // for comparison with the compare index such as S&P500 index. // Stock value starts at zero, and cash value becomes close to zero, // so they fluctuation widely, so leave them out. XYDataset accountTotalPercentData = new XYDatasetPercentChangeAdapter( new SubSeriesDataset(accountData, BalanceHistoryXYDataset.TOTAL_SERIES)); XYLineAndShapeRenderer compareRenderer = new XYLineAndShapeRenderer(); compareRenderer.setShapesVisible(useShapes); XYPlot comparePlot = new XYPlot(accountTotalPercentData, dateAxis, percentAxis, compareRenderer); String compareIndexSymbol = this.compareIndexSymbolField.getText(); StockHistory compareHistory = this.histories.get(compareIndexSymbol); if (compareHistory != null) { XYDataset comparePercentData = new OHLCDatasetPercentChangeAdapter(new OHLCDatasetSubdomainAdapter( new OHLCDatasetOfStockHistory(compareHistory), startDate, endDate)); int compareIndex = 1; comparePlot.setDataset(compareIndex, comparePercentData); XYLineAndShapeRenderer percentRenderer = new XYLineAndShapeRenderer(); percentRenderer.setShapesVisible(useShapes); comparePlot.setRenderer(compareIndex, percentRenderer); } // share date axis CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(dateAxis); combinedPlot.add(comparePlot, 1); combinedPlot.add(accountPlot, 1); this.chartPanel.setChart(new JFreeChart(title, null, combinedPlot, true)); return new NumberAxis[] { priceAxis, percentAxis }; }
From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java
private byte[] generateTimeSeriesChart(String siteId, IntervalXYDataset dataset, int width, int height, boolean renderBar, float transparency, boolean itemLabelsVisible, boolean smallFontInDomainAxis, String timePeriod, Date firstDate, Date lastDate) { JFreeChart chart = null;/*from w ww . j a v a2s .com*/ if (!renderBar) { chart = ChartFactory.createTimeSeriesChart(null, null, null, dataset, true, false, false); } else { chart = ChartFactory.createXYBarChart(null, null, true, null, dataset, PlotOrientation.VERTICAL, true, false, false); } XYPlot plot = (XYPlot) chart.getPlot(); // set transparency plot.setForegroundAlpha(transparency); // set background chart.setBackgroundPaint(parseColor(M_sm.getChartBackgroundColor())); // set chart border chart.setPadding(new RectangleInsets(10, 5, 5, 5)); chart.setBorderVisible(true); chart.setBorderPaint(parseColor("#cccccc")); // set antialias chart.setAntiAlias(true); // set domain axis font size if (smallFontInDomainAxis && !canUseNormalFontSize(width)) { plot.getDomainAxis().setTickLabelFont(new Font("SansSerif", Font.PLAIN, 8)); } // configure date display (localized) in domain axis Locale locale = msgs.getLocale(); PeriodAxis periodaxis = new PeriodAxis(null); Class timePeriodClass = null; if (dataset instanceof TimeSeriesCollection) { TimeSeriesCollection tsc = (TimeSeriesCollection) dataset; if (tsc.getSeriesCount() > 0) { timePeriodClass = tsc.getSeries(0).getTimePeriodClass(); } else { timePeriodClass = org.jfree.data.time.Day.class; } periodaxis.setAutoRangeTimePeriodClass(timePeriodClass); } PeriodAxisLabelInfo aperiodaxislabelinfo[] = null; if (StatsManager.CHARTTIMESERIES_WEEKDAY.equals(timePeriod)) { aperiodaxislabelinfo = new PeriodAxisLabelInfo[2]; aperiodaxislabelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Day.class, new SimpleDateFormat("E", locale)); aperiodaxislabelinfo[1] = new PeriodAxisLabelInfo(org.jfree.data.time.Day.class, new SimpleDateFormat("d", locale)); } else if (StatsManager.CHARTTIMESERIES_DAY.equals(timePeriod)) { aperiodaxislabelinfo = new PeriodAxisLabelInfo[3]; aperiodaxislabelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Day.class, new SimpleDateFormat("d", locale)); aperiodaxislabelinfo[1] = new PeriodAxisLabelInfo(org.jfree.data.time.Month.class, new SimpleDateFormat("MMM", locale)); aperiodaxislabelinfo[2] = new PeriodAxisLabelInfo(org.jfree.data.time.Year.class, new SimpleDateFormat("yyyy", locale)); } else if (StatsManager.CHARTTIMESERIES_MONTH.equals(timePeriod)) { aperiodaxislabelinfo = new PeriodAxisLabelInfo[2]; aperiodaxislabelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Month.class, new SimpleDateFormat("MMM", locale)); aperiodaxislabelinfo[1] = new PeriodAxisLabelInfo(org.jfree.data.time.Year.class, new SimpleDateFormat("yyyy", locale)); } else if (StatsManager.CHARTTIMESERIES_YEAR.equals(timePeriod)) { aperiodaxislabelinfo = new PeriodAxisLabelInfo[1]; aperiodaxislabelinfo[0] = new PeriodAxisLabelInfo(org.jfree.data.time.Year.class, new SimpleDateFormat("yyyy", locale)); } periodaxis.setLabelInfo(aperiodaxislabelinfo); // date range if (firstDate != null || lastDate != null) { periodaxis.setAutoRange(false); if (firstDate != null) { if (StatsManager.CHARTTIMESERIES_MONTH.equals(timePeriod) || StatsManager.CHARTTIMESERIES_YEAR.equals(timePeriod)) { periodaxis.setFirst(new org.jfree.data.time.Month(firstDate)); } else { periodaxis.setFirst(new org.jfree.data.time.Day(firstDate)); } } if (lastDate != null) { if (StatsManager.CHARTTIMESERIES_MONTH.equals(timePeriod) || StatsManager.CHARTTIMESERIES_YEAR.equals(timePeriod)) { periodaxis.setLast(new org.jfree.data.time.Month(lastDate)); } else { periodaxis.setLast(new org.jfree.data.time.Day(lastDate)); } } } periodaxis.setTickMarkOutsideLength(0.0F); plot.setDomainAxis(periodaxis); // set outline AbstractXYItemRenderer renderer = (AbstractXYItemRenderer) plot.getRenderer(); if (renderer instanceof XYLineAndShapeRenderer) { XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) renderer; r.setDrawSeriesLineAsPath(true); r.setShapesVisible(true); r.setShapesFilled(true); } else if (renderer instanceof XYBarRenderer) { //XYBarRenderer r = (XYBarRenderer) renderer; ClusteredXYBarRenderer r = new ClusteredXYBarRenderer(); r.setDrawBarOutline(true); if (smallFontInDomainAxis && !canUseNormalFontSize(width)) r.setMargin(0.05); else r.setMargin(0.10); plot.setRenderer(r); renderer = r; } // item labels if (itemLabelsVisible) { plot.getRangeAxis().setUpperMargin(0.2); renderer.setItemLabelGenerator(new XYItemLabelGenerator() { private static final long serialVersionUID = 1L; public String generateLabel(XYDataset dataset, int series, int item) { Number n = dataset.getY(series, item); if (n.doubleValue() != 0) return n.toString(); return ""; } }); renderer.setItemLabelFont(new Font("SansSerif", Font.PLAIN, 8)); renderer.setItemLabelsVisible(true); } BufferedImage img = chart.createBufferedImage(width, height); final ByteArrayOutputStream out = new ByteArrayOutputStream(); try { ImageIO.write(img, "png", out); } catch (IOException e) { LOG.warn("Error occurred while generating SiteStats chart image data", e); } return out.toByteArray(); }
From source file:src.planning.PlanSimulator.java
public static List<ChartPanel> drawCharts(Element analysis, Element problem) { List<ChartPanel> charts = new ArrayList<ChartPanel>(); // draw the charts List<?> variables = analysis.getChild("variables").getChildren("variable"); for (Iterator<?> iter = variables.iterator(); iter.hasNext();) { Element variable = (Element) iter.next(); Element domainObject = null; try {//from w w w . j a va 2 s . co m XPath path = new JDOMXPath("elements/objects/object[@id='" + variable.getChild("object").getAttributeValue("id") + "']"); domainObject = (Element) path.selectSingleNode(problem.getParentElement().getParentElement()); } catch (JaxenException e) { e.printStackTrace(); } Element attribute = variable.getChild("object").getChild("attribute"); Element classAttr = null; try { XPath path = new JDOMXPath( "project/elements/classes/class[@id='" + attribute.getAttributeValue("class") + "']/attributes/attribute[@id='" + attribute.getAttributeValue("id") + "']"); classAttr = (Element) path.selectSingleNode(problem.getDocument()); } catch (JaxenException e) { e.printStackTrace(); } String chartTitle = domainObject.getChildText("name") + "." + classAttr.getChildText("name"); if (variable.getAttributeValue("type").equals("attr")) { // attribute String attrType = variable.getChild("object").getChild("attribute").getAttributeValue("type"); if (attrType.equals("1")) { //BOOLEAN attribute XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries series = new XYSeries("Boolean"); int stepIndex = 0; for (Iterator<?> iterator = variable.getChild("values").getChildren("value") .iterator(); iterator.hasNext();) { Element value = (Element) iterator.next(); series.add(stepIndex++, (value.getText().equals("false") ? 0 : 1)); } dataset.addSeries(series); JFreeChart chart = ChartFactory.createXYStepChart(chartTitle, "Values", "Steps", dataset, PlotOrientation.VERTICAL, false, true, false); XYPlot plot = (XYPlot) chart.getPlot(); NumberAxis domainAxis = new NumberAxis("Steps"); domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); domainAxis.setAutoRangeIncludesZero(false); plot.setDomainAxis(domainAxis); String[] values = { "false", "true" }; SymbolAxis rangeAxis = new SymbolAxis("Values", values); plot.setRangeAxis(rangeAxis); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new Dimension(chartPanel.getSize().width, 175)); charts.add(chartPanel); } else if (attrType.equals("2") || attrType.equals("3")) { //NUMERIC attributes XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries series = new XYSeries("variable"); int stepIndex = 0; for (Iterator<?> iterator = variable.getChild("values").getChildren("value") .iterator(); iterator.hasNext();) { Element value = (Element) iterator.next(); series.add(stepIndex++, Double.parseDouble(value.getText())); } dataset.addSeries(series); JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, "Steps", "Values", dataset, PlotOrientation.VERTICAL, false, true, false); XYPlot xyPlot = (XYPlot) chart.getPlot(); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyPlot.getRenderer(); renderer.setShapesVisible(true); renderer.setShapesFilled(true); NumberAxis rangeAxis = (NumberAxis) xyPlot.getRangeAxis(); rangeAxis.setAutoRangeIncludesZero(true); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); if (attrType.equals("2")) { NumberAxis domainAxis = (NumberAxis) xyPlot.getDomainAxis(); domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); } ChartPanel chartPanel = new ChartPanel(chart); charts.add(chartPanel); } else if (!attrType.equals("4")) {//NOT PRIMITIVE attributes Element attrClass = null; try { XPath path = new JDOMXPath( "project/elements/classes/class[@id='" + classAttr.getChildText("type") + "']"); attrClass = (Element) path.selectSingleNode(problem.getDocument()); } catch (JaxenException e) { e.printStackTrace(); } if (attrClass != null) { List<Element> classes = XMLUtilities.getClassDescendents(attrClass); String query = "elements/objects/object["; for (Iterator<?> iterator = classes.iterator(); iterator.hasNext();) { Element childClass = (Element) iterator.next(); query += "class='" + childClass.getAttributeValue("id") + "'"; query += " or ";// the last or is for the parent class } query += "class='" + attrClass.getAttributeValue("id") + "']"; // get all the objects of all descendant classes, including the parent class List<?> objects = null; try { XPath path = new JDOMXPath(query); objects = path.selectNodes(problem.getParentElement().getParentElement()); } catch (JaxenException e) { e.printStackTrace(); } if (objects.size() > 0) { //build a list with all the objects names String[] names = new String[objects.size() + 1];// the array is for the axis names[0] = "null";// default null value List<String> objectNames = new ArrayList<String>(); int i = 1; for (Iterator<?> iterator = objects.iterator(); iterator.hasNext();) { Element object = (Element) iterator.next(); names[i++] = object.getChildText("name"); objectNames.add(object.getChildText("name").toLowerCase()); } XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries series = new XYSeries("Objects"); int stepIndex = 0; for (Iterator<?> iterator = variable.getChild("values").getChildren("value") .iterator(); iterator.hasNext();) { Element value = (Element) iterator.next(); series.add(stepIndex++, objectNames.indexOf(value.getText().toLowerCase()) + 1); } dataset.addSeries(series); // draw the chart JFreeChart chart = ChartFactory.createXYStepChart(chartTitle, "Objects", "Steps", dataset, PlotOrientation.VERTICAL, false, true, false); XYPlot plot = (XYPlot) chart.getPlot(); NumberAxis domainAxis = new NumberAxis("Steps"); domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); domainAxis.setAutoRangeIncludesZero(false); plot.setDomainAxis(domainAxis); SymbolAxis rangeAxis = new SymbolAxis("Objects", names); plot.setRangeAxis(rangeAxis); ChartPanel chartPanel = new ChartPanel(chart); charts.add(chartPanel); } } } } } return charts; }