List of usage examples for org.jfree.chart.plot XYPlot setDomainAxis
public void setDomainAxis(ValueAxis axis)
From source file:org.matsim.pt.counts.obsolete.PtCountsSimRealPerHourGraph.java
/** * @param hour// w w w . jav a 2 s. c o m * A value in 1..24, 1 for 0 a.m. to 1 a.m., 2 for 1 a.m. to 2 * a.m. ... */ @Override @Deprecated // use standard counts package public JFreeChart createChart(final int hour) { this.hour = hour; XYSeriesCollection dataset0 = new XYSeriesCollection(); XYSeries series = new XYSeries("MATSim volumes"); // easier to use another dataset XYSeriesCollection dataset_outliers = new XYSeriesCollection(); XYSeries series_outliers = new XYSeries("MATSim outliers"); CustomXYURLGenerator url_gen = new CustomXYURLGenerator(); CustomXYToolTipGenerator tt_gen = new CustomXYToolTipGenerator(); final ArrayList<String> urls = new ArrayList<String>(); final ArrayList<String> tooltips = new ArrayList<String>(); List<Comp> comps = new Vector<Comp>(); Iterator<CountSimComparison> l_it = this.ccl_.iterator(); // int elementCounter=0; while (l_it.hasNext()) { CountSimComparison cc = l_it.next(); /* * values with simVal==0.0 or countVal==0.0 are drawn on the x==1 * or/and y==1-line Such values are the result of a poor simulation * run, but they can also represent a valid result (closing summer * road during winter time) */ if (cc.getHour() == hour) { // elementCounter++; double realVal = 1.0; double simVal = 1.0; if (cc.getCountValue() > 0.0 && cc.getSimulationValue() > 0.0) { realVal = cc.getCountValue(); simVal = cc.getSimulationValue(); series.add(realVal, simVal); comps.add(new Comp(realVal, "link" + cc.getId() + ".html", "Link " + cc.getId() + "; " + "Count: " + realVal + ", Sim: " + simVal)); } else { realVal = Math.max(1.0, cc.getCountValue()); simVal = Math.max(1.0, cc.getSimulationValue()); series_outliers.add(realVal, simVal); } } // if } // while dataset0.addSeries(series); dataset_outliers.addSeries(series_outliers); /* * first we have to sort the vector according to the rendering ordering * (which is the x value). REALLY??? After hours of searching no better * solution found! please help! */ Collections.sort(comps, new MyComparator()); for (Iterator<Comp> iter = comps.iterator(); iter.hasNext();) { Comp cp = iter.next(); urls.add(cp.getURL()); tooltips.add(cp.getTooltip()); } url_gen.addURLSeries(urls); tt_gen.addToolTipSeries(tooltips); String title = "[" + this.countsType + "]\tVolumes " + (hour - 1) + ":00 - " + (hour) + ":00, Iteration: " + this.iteration_; this.setChartTitle(title); this.chart_ = ChartFactory.createXYLineChart(title, "Count Volumes [veh/h]", // x axis label "Sim Volumes [veh/h]", // y axis label dataset0, // data PlotOrientation.VERTICAL, false, // include legend true, // tooltips true // urls ); XYPlot plot = this.chart_.getXYPlot(); final LogarithmicAxis axis_x = new LogarithmicAxis("Count Volumes [veh/h]"); final LogarithmicAxis axis_y = new LogarithmicAxis("Sim Volumes [veh/h]"); axis_x.setAllowNegativesFlag(false); axis_y.setAllowNegativesFlag(false); // regular values XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); renderer.setLinesVisible(false); renderer.setURLGenerator(url_gen); renderer.setSeriesPaint(0, Color.black); renderer.setSeriesToolTipGenerator(0, tt_gen); renderer.setSeriesShape(0, new Rectangle2D.Double(-1.5, -1.5, 3.0, 3.0)); // outliers XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(); renderer2.setLinesVisible(false); renderer2.setSeriesPaint(0, Color.red); renderer2.setSeriesShape(0, new Ellipse2D.Double(-3.0, -3.0, 6.0, 6.0)); // error band DefaultXYDataset dataset1 = new DefaultXYDataset(); dataset1.addSeries("f1x", new double[][] { { 1.0, 10000.0 }, { 1.0, 10000.0 } }); dataset1.addSeries("f2x", new double[][] { { 1.0, 10000.0 }, { 2.0, 20000.0 } }); dataset1.addSeries("f05x", new double[][] { { 2.0, 10000.0 }, { 1.0, 5000.0 } }); XYLineAndShapeRenderer renderer3 = new XYLineAndShapeRenderer(); renderer3.setShapesVisible(false); renderer3.setSeriesPaint(0, Color.blue); renderer3.setSeriesPaint(1, Color.blue); renderer3.setSeriesPaint(2, Color.blue); renderer3.setBaseSeriesVisibleInLegend(false); renderer3.setSeriesItemLabelsVisible(0, true); renderer3.setSeriesItemLabelsVisible(1, false); renderer3.setSeriesItemLabelsVisible(2, false); XYTextAnnotation annotation0 = new XYTextAnnotation("2.0 count", 12000.0, 15500.0); annotation0.setFont(new Font("SansSerif", Font.BOLD, 11)); plot.addAnnotation(annotation0); XYTextAnnotation annotation1 = new XYTextAnnotation("count", 13000.0, 10000.0); annotation1.setFont(new Font("SansSerif", Font.BOLD, 11)); plot.addAnnotation(annotation1); XYTextAnnotation annotation2 = new XYTextAnnotation("0.5 count", 11000.0, 3500.0); annotation2.setFont(new Font("SansSerif", Font.BOLD, 11)); plot.addAnnotation(annotation2); plot.setDomainAxis(axis_x); plot.setRangeAxis(axis_y); plot.setRenderer(0, renderer); plot.setRenderer(1, renderer2); plot.setDataset(1, dataset_outliers); plot.setRenderer(2, renderer3); plot.setDataset(2, dataset1); plot.getRangeAxis().setRange(1.0, 19000.0); plot.getDomainAxis().setRange(1.0, 19000.0); return this.chart_; }
From source file:org.matsim.counts.algorithms.graphs.CountsSimReal24Graph.java
@Override public JFreeChart createChart(final int nbr) { XYSeriesCollection dataset0 = new XYSeriesCollection(); XYSeries series = new XYSeries("MATSim volumes"); // easier to use another dataset XYSeriesCollection dataset_outliers = new XYSeriesCollection(); XYSeries series_outliers = new XYSeries("MATSim outliers"); CustomXYURLGenerator url_gen = new CustomXYURLGenerator(); CustomXYToolTipGenerator tt_gen = new CustomXYToolTipGenerator(); final ArrayList<String> urls = new ArrayList<>(); final ArrayList<String> tooltips = new ArrayList<>(); List<Comp> comps = new Vector<>(); //-------------------- CountSimComparisonLinkFilter linkFilter = new CountSimComparisonLinkFilter(this.ccl_); final Vector<Id<Link>> linkIds = new CountSimComparisonLinkFilter(this.ccl_).getLinkIds(); Iterator<Id<Link>> id_it = linkIds.iterator(); double maxCountValue = 0.1; double maxSimValue = 0.1; // yyyy PtCountsKMLWriterTest.testPtAlightKMLCreation never touches these and then leads to an exception later // when they are zero. Don't know why. kai, sep'16 while (id_it.hasNext()) { Id<Link> id = id_it.next(); double countVal = linkFilter.getAggregatedCountValue(id); double simVal = linkFilter.getAggregatedSimValue(id); if (countVal > 100.0 && simVal > 100.0) { if (countVal > maxCountValue) maxCountValue = countVal; if (simVal > maxSimValue) maxSimValue = simVal;/*from w ww.j ava2 s. co m*/ series.add(countVal, simVal); comps.add(new Comp(countVal, "link" + id + ".html", "Link " + id + "; " + "Count: " + countVal + ", Sim: " + simVal)); } else { /* values with simVal<100.0 or countVal<100.0 are drawn on the x==100 or/and y==100-line */ countVal = Math.max(100.0, countVal); simVal = Math.max(100.0, simVal); series_outliers.add(countVal, simVal); if (countVal > maxCountValue) maxCountValue = countVal; if (simVal > maxSimValue) maxSimValue = simVal; } } //while dataset0.addSeries(series); dataset_outliers.addSeries(series_outliers); Collections.sort(comps, new MyComparator()); for (Iterator<Comp> iter = comps.iterator(); iter.hasNext();) { Comp cp = iter.next(); urls.add(cp.getURL()); tooltips.add(cp.getTooltip()); } url_gen.addURLSeries(urls); tt_gen.addToolTipSeries(tooltips); String title = "Avg. Weekday Traffic Volumes, Iteration: " + this.iteration_; this.setChartTitle(title); this.chart_ = ChartFactory.createXYLineChart(title, "Count Volumes", // x axis label "Sim Volumes", // y axis label dataset0, // data PlotOrientation.VERTICAL, false, // include legend true, // tooltips true // urls ); XYPlot plot = this.chart_.getXYPlot(); final LogarithmicAxis axis_x = new LogarithmicAxis("Count Volumes [veh/24h]"); final LogarithmicAxis axis_y = new LogarithmicAxis("Sim Volumes [veh/24h]"); axis_x.setAllowNegativesFlag(false); axis_y.setAllowNegativesFlag(false); //regular values XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); renderer.setLinesVisible(false); renderer.setURLGenerator(url_gen); renderer.setSeriesPaint(0, Color.black); renderer.setSeriesToolTipGenerator(0, tt_gen); renderer.setSeriesShape(0, new Rectangle2D.Double(-1.5, -1.5, 3.0, 3.0)); //outliers XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer(); renderer2.setLinesVisible(false); renderer2.setSeriesPaint(0, Color.red); renderer2.setSeriesShape(0, new Ellipse2D.Double(-3.0, -3.0, 6.0, 6.0)); // error band DefaultXYDataset dataset1 = new DefaultXYDataset(); Gbl.assertIf(maxCountValue > 0.); dataset1.addSeries("f1x", new double[][] { { 100.0, maxCountValue }, { 100.0, maxCountValue } }); dataset1.addSeries("f2x", new double[][] { { 100.0, maxCountValue }, { 200.0, 2 * maxCountValue } }); dataset1.addSeries("f05x", new double[][] { { 200.0, maxCountValue }, { 100.0, 0.5 * maxCountValue } }); XYLineAndShapeRenderer renderer3 = new XYLineAndShapeRenderer(); renderer3.setShapesVisible(false); renderer3.setSeriesPaint(0, Color.blue); renderer3.setSeriesPaint(1, Color.blue); renderer3.setSeriesPaint(2, Color.blue); renderer3.setBaseSeriesVisibleInLegend(false); renderer3.setSeriesItemLabelsVisible(0, true); renderer3.setSeriesItemLabelsVisible(1, false); renderer3.setSeriesItemLabelsVisible(2, false); XYTextAnnotation annotation0 = new XYTextAnnotation("2.0 count", maxCountValue, 2 * maxCountValue); annotation0.setFont(new Font("SansSerif", Font.BOLD, 11)); plot.addAnnotation(annotation0); XYTextAnnotation annotation1 = new XYTextAnnotation("count", maxCountValue, maxCountValue); annotation1.setFont(new Font("SansSerif", Font.BOLD, 11)); plot.addAnnotation(annotation1); XYTextAnnotation annotation2 = new XYTextAnnotation("0.5 count", maxCountValue, 0.5 * maxCountValue); annotation2.setFont(new Font("SansSerif", Font.BOLD, 11)); plot.addAnnotation(annotation2); plot.setDomainAxis(axis_x); plot.setRangeAxis(axis_y); plot.setRenderer(0, renderer); plot.setRenderer(1, renderer2); plot.setDataset(1, dataset_outliers); plot.setRenderer(2, renderer3); plot.setDataset(2, dataset1); //plot.getRangeAxis().setRange(1.0, 19000.0); //plot.getDomainAxis().setRange(1.0, 19000.0); return this.chart_; }
From source file:com.chart.SwingChart.java
/** * // w ww. j ava2 s . c o m * @param name Chart name * @param parent Skeleton parent * @param axes Configuration of axes * @param abcissaName Abcissa name */ public SwingChart(String name, final Skeleton parent, List<AxisChart> axes, String abcissaName) { this.skeleton = parent; this.axes = axes; this.name = name; this.abcissaFormat = NumberFormat.getInstance(Locale.getDefault()); this.ordinateFormat = NumberFormat.getInstance(Locale.getDefault()); plot = new XYPlot(); plot.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strChartBackgroundColor))); plot.setDomainGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor))); plot.setRangeGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor))); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); abcissaAxis = new NumberAxis(abcissaName); ((NumberAxis) abcissaAxis).setAutoRangeIncludesZero(false); abcissaAxis.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12)); abcissaAxis.setLabelFont(new Font("SansSerif", Font.PLAIN, 12)); abcissaAxis.setLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor))); abcissaAxis.setTickLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor))); abcissaAxis.setAutoRange(true); abcissaAxis.setLowerMargin(0.0); abcissaAxis.setUpperMargin(0.0); abcissaAxis.setTickLabelsVisible(true); abcissaAxis.setLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize)); abcissaAxis.setTickLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize)); plot.setDomainAxis(abcissaAxis); for (int i = 0; i < axes.size(); i++) { AxisChart categoria = axes.get(i); addAxis(categoria.getName()); for (int j = 0; j < categoria.configSerieList.size(); j++) { SimpleSeriesConfiguration cs = categoria.configSerieList.get(j); addSeries(categoria.getName(), cs); } } chart = new JFreeChart("", new Font("SansSerif", Font.BOLD, 16), plot, false); chart.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor))); chartPanel = new ChartPanel(chart); chartPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4), BorderFactory.createLineBorder(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor))))); chartPanel.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "escape"); chartPanel.getActionMap().put("escape", new AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { for (int i = 0; i < plot.getDatasetCount(); i++) { XYDataset test = plot.getDataset(i); XYItemRenderer r = plot.getRenderer(i); r.removeAnnotations(); } } }); chartPanel.addChartMouseListener(cml = new ChartMouseListener() { @Override public void chartMouseClicked(ChartMouseEvent event) { } @Override public void chartMouseMoved(ChartMouseEvent event) { try { XYItemEntity xyitem = (XYItemEntity) event.getEntity(); // get clicked entity XYDataset dataset = (XYDataset) xyitem.getDataset(); // get data set double x = dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()); double y = dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()); final XYPlot plot = chart.getXYPlot(); for (int i = 0; i < plot.getDatasetCount(); i++) { XYDataset test = plot.getDataset(i); XYItemRenderer r = plot.getRenderer(i); r.removeAnnotations(); if (test == dataset) { NumberAxis ejeOrdenada = AxesList.get(i); double y_max = ejeOrdenada.getUpperBound(); double y_min = ejeOrdenada.getLowerBound(); double x_max = abcissaAxis.getUpperBound(); double x_min = abcissaAxis.getLowerBound(); double angulo; if (y > (y_max + y_min) / 2 && x > (x_max + x_min) / 2) { angulo = 3.0 * Math.PI / 4.0; } else if (y > (y_max + y_min) / 2 && x < (x_max + x_min) / 2) { angulo = 1.0 * Math.PI / 4.0; } else if (y < (y_max + y_min) / 2 && x < (x_max + x_min) / 2) { angulo = 7.0 * Math.PI / 4.0; } else { angulo = 5.0 * Math.PI / 4.0; } CircleDrawer cd = new CircleDrawer((Color) r.getSeriesPaint(xyitem.getSeriesIndex()), new BasicStroke(2.0f), null); //XYAnnotation bestBid = new XYDrawableAnnotation(dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()), dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()), 11, 11, cd); String txt = "X:" + abcissaFormat.format(x) + ", Y:" + ordinateFormat.format(y); XYPointerAnnotation anotacion = new XYPointerAnnotation(txt, dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()), dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()), angulo); anotacion.setTipRadius(10.0); anotacion.setBaseRadius(35.0); anotacion.setFont(new Font("SansSerif", Font.PLAIN, 10)); if (Long.parseLong((strChartBackgroundColor.replace("#", "")), 16) > 0xffffff / 2) { anotacion.setPaint(Color.black); anotacion.setArrowPaint(Color.black); } else { anotacion.setPaint(Color.white); anotacion.setArrowPaint(Color.white); } //bestBid.setPaint((Color) r.getSeriesPaint(xyitem.getSeriesIndex())); r.addAnnotation(anotacion); } } //LabelValorVariable.setSize(LabelValorVariable.getPreferredSize()); } catch (NullPointerException | ClassCastException ex) { } } }); chartPanel.setPopupMenu(null); chartPanel.setBackground(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor))); SwingNode sn = new SwingNode(); sn.setContent(chartPanel); chartFrame = new VBox(); chartFrame.getChildren().addAll(sn, legendFrame); VBox.setVgrow(sn, Priority.ALWAYS); VBox.setVgrow(legendFrame, Priority.NEVER); chartFrame.getStylesheets().addAll(SwingChart.class.getResource("overlay-chart.css").toExternalForm()); legendFrame.setStyle("marco: " + strBackgroundColor + ";-fx-background-color: marco;"); MenuItem mi; mi = new MenuItem("Print"); mi.setOnAction((ActionEvent t) -> { print(chartFrame); }); contextMenuList.add(mi); sn.setOnMouseClicked((MouseEvent t) -> { if (menu != null) { menu.hide(); } if (t.getClickCount() == 2) { backgroundEdition(); } }); mi = new MenuItem("Copy to clipboard"); mi.setOnAction((ActionEvent t) -> { copyClipboard(chartFrame); }); contextMenuList.add(mi); mi = new MenuItem("Export values"); mi.setOnAction((ActionEvent t) -> { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Export to file"); fileChooser.getExtensionFilters() .addAll(new FileChooser.ExtensionFilter("Comma Separated Values", "*.csv")); Window w = null; try { w = parent.getScene().getWindow(); } catch (NullPointerException e) { } File file = fileChooser.showSaveDialog(w); if (file != null) { export(file); } }); contextMenuList.add(mi); chartFrame.setOnContextMenuRequested((ContextMenuEvent t) -> { if (menu != null) { menu.hide(); } menu = new ContextMenu(); menu.getItems().addAll(contextMenuList); menu.show(chartFrame, t.getScreenX(), t.getScreenY()); }); }
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 ww w . ja v a 2 s.c o 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; }
From source file:osh.comdriver.simulation.cruisecontrol.ScheduleDrawer.java
/** * Creates a chart.// w ww . ja v a 2 s . c o m * * @param dataset1 a dataset. * @return A chart. */ private static JFreeChart createChart(XYDataset dataset1, //power XYDataset dataset2, //costs XYDataset dataset3, long time) { JFreeChart chart = ChartFactory.createTimeSeriesChart("schedule", // title "time", // x-axis label "power", // y-axis label dataset1, // data true, // create legend? true, // generate tooltips? false // generate URLs? ); chart.setBackgroundPaint(Color.white); XYPlot plot = (XYPlot) chart.getPlot(); NumberAxis axis1 = new NumberAxis("power"); NumberAxis axis2 = new NumberAxis("costs"); axis1.setAutoRangeIncludesZero(true); axis1.setUpperBound(5000); axis1.setLowerBound(-5000); axis2.setAutoRangeIncludesZero(true); axis2.setUpperBound(50); axis2.setLowerBound(0); plot.setRangeAxis(0, axis1); plot.setRangeAxis(1, axis2); plot.setDataset(1, dataset2); plot.mapDatasetToRangeAxis(1, 1); plot.setDataset(2, dataset3); plot.mapDatasetToRangeAxis(2, 0); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.setDomainCrosshairVisible(true); plot.setRangeCrosshairVisible(true); //TODO: SHADOWS OFF final StandardXYItemRenderer r1 = new StandardXYItemRenderer(); final StandardXYItemRenderer r2 = new StandardXYItemRenderer(); final StandardXYItemRenderer r3 = new StandardXYItemRenderer(); final StandardXYItemRenderer r4 = new StandardXYItemRenderer(); plot.setRenderer(0, r1); plot.setRenderer(1, r2); plot.setRenderer(2, r3); plot.setRenderer(3, r4); int numberOfSeries = 0; numberOfSeries += dataset1.getSeriesCount(); numberOfSeries += dataset2.getSeriesCount(); numberOfSeries += dataset3.getSeriesCount(); Color[] color = new Color[numberOfSeries]; for (int i = 0; i < numberOfSeries / 2; i++) { color[i] = Color.getHSBColor(i * 1.0f / (numberOfSeries / 2), 1.0f, 1.0f); } int i = 0; for (int j = 0; j < dataset1.getSeriesCount() / 2; j++) { float[] rgbcolor = Color.RGBtoHSB(color[i].getRed(), color[i].getGreen(), color[i].getBlue(), null); plot.getRendererForDataset(dataset1).setSeriesPaint(2 * j, Color.getHSBColor(rgbcolor[0], 1.0f, 1.0f)); plot.getRendererForDataset(dataset1).setSeriesPaint(2 * j + 1, Color.getHSBColor(rgbcolor[0], 1.0f, 0.6f)); i++; } for (int j = 0; j < dataset2.getSeriesCount() / 2; j++) { float[] rgbcolor = Color.RGBtoHSB(color[i].getRed(), color[i].getGreen(), color[i].getBlue(), null); plot.getRendererForDataset(dataset2).setSeriesPaint(2 * j, Color.getHSBColor(rgbcolor[0], 1.0f, 1.0f)); plot.getRendererForDataset(dataset2).setSeriesPaint(2 * j + 1, Color.getHSBColor(rgbcolor[0], 1.0f, 0.6f)); i++; } for (int j = 0; j < dataset3.getSeriesCount() / 2; j++) { float[] rgbcolor = Color.RGBtoHSB(color[i].getRed(), color[i].getGreen(), color[i].getBlue(), null); plot.getRendererForDataset(dataset3).setSeriesPaint(2 * j, Color.getHSBColor(rgbcolor[0], 1.0f, 1.0f)); plot.getRendererForDataset(dataset3).setSeriesPaint(2 * j + 1, Color.getHSBColor(rgbcolor[0], 1.0f, 0.6f)); i++; } // NOW line double upperBound = plot.getRangeAxis(1).getUpperBound(); double lowerBound = plot.getRangeAxis(1).getLowerBound(); XYSeries nowLine = new XYSeries("now"); nowLine.add(time * 1000, lowerBound); nowLine.add(time * 1000, upperBound); XYSeriesCollection nowColl = new XYSeriesCollection(); //power axis nowColl.addSeries(nowLine); XYDataset nowSet = nowColl; plot.setDataset(3, nowSet); plot.mapDatasetToRangeAxis(3, 1); plot.getRendererForDataset(nowSet).setSeriesPaint(0, Color.DARK_GRAY); plot.getRendererForDataset(nowSet).setSeriesStroke(0, (Stroke) new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] { 6.0f, 6.0f }, 0.0f)); plot.setDomainAxis(new DateAxis()); plot.getDomainAxis().setAutoRange(false); long begin = (time / 86400) * 86400 * 1000; //beginning of day long end = begin + 86400 * 2 * 1000; plot.getDomainAxis().setRange(begin, end); return chart; }
From source file:org.fhcrc.cpl.viewer.gui.MRMDialog.java
/** * Draw a chart in a panel. Good for precursors and daughters * @param parentPanel//from w w w.j av a 2 s . c om * @param dataset * @param domainMin * @param domainMax * @param supplier * @param wg */ protected void createChartInPanel(JPanel parentPanel, XYSeriesCollection dataset, Double domainMin, Double domainMax, DrawingSupplier supplier, whichGraph wg) { if (precursorChromatogramEmpty(transitionOnPlot) && wg == whichGraph.Precursor) { precursorContainerContainerPanel.setVisible(false); if (this.getWidth() >= 100 && this.getHeight() >= 100) this.setPreferredSize(new Dimension(this.getWidth(), this.getHeight())); pack(); return; } switch (wg) { case Precursor: clearPreviousChartJunk(oldPrecursorChart); oldPrecursorChart = null; break; case Daughter: clearPreviousChartJunk(oldProductChart); oldProductChart = null; break; } JFreeChart chart = ChartFactory.createXYLineChart(null, "seconds", null, dataset, PlotOrientation.VERTICAL, true, false, false); chart.setBackgroundPaint(new Color(220, 220, 220)); XYPlot xyp = (XYPlot) (chart.getPlot()); xyp.setBackgroundPaint(Color.WHITE); xyp.setDomainGridlinesVisible(true); xyp.setRangeGridlinesVisible(true); xyp.setDomainGridlinePaint(Color.LIGHT_GRAY); xyp.setRangeGridlinePaint(Color.LIGHT_GRAY); if (supplier != null) { xyp.setDrawingSupplier(supplier); } else { xyp.setDrawingSupplier(Utils.plainDrawingSupplier(Color.LIGHT_GRAY)); } xyp.setSeriesRenderingOrder(SeriesRenderingOrder.REVERSE); CenterZoomNumberAxis axisDomain = new CenterZoomNumberAxis("seconds"); axisDomain.setAutoRangeIncludesZero(false); axisDomain.setRange(Math.max(0.0, domainMin), domainMax); axisDomain.addChangeListener(new domainAxisZoomCoordinator(axisDomain)); xyp.clearAnnotations(); xyp.setDomainAxis(axisDomain); xyp.getDomainAxis().setAutoRange(false); xyp.getRangeAxis().setAutoRange(false); XYLineAndShapeRenderer xylsr = (XYLineAndShapeRenderer) xyp.getRenderer(); xylsr.setLegendLine(Utils.legendThing(16, 6)); xylsr.setShapesFilled(true); xylsr.setBaseShapesFilled(true); PanelWithChart panelWithChart = new PanelWithChart(chart); ChartPanel cp = panelWithChart.getChartPanel(); cp.removeMouseListener(cp); cp.removeMouseMotionListener(cp); if (peaksTable != null) { MRMerMouseListener mml = new MRMerMouseListener(cp, (PeaksTableModel) peaksTable.getModel()); cp.addMouseListener(mml); cp.addMouseMotionListener(mml); } cp.setPreferredSize(new Dimension(parentPanel.getWidth(), parentPanel.getHeight() - 10)); cp.setDomainZoomable(true); cp.setRangeZoomable(false); cp.setPopupMenu(null); parentPanel.removeAll(); parentPanel.add(panelWithChart); switch (wg) { case Precursor: createChartInPanelPrecursorTasksOnly(xyp); oldPrecursorChart = xyp; break; case Daughter: createChartInPanelDaughterTasksOnly(xyp); oldProductChart = xyp; break; } parentPanel.updateUI(); listTransition.requestFocus(); }
From source file:edu.ucla.stat.SOCR.chart.ChartGenerator_JTable.java
/** * *//*w w w. j a v a 2 s .c om*/ private void setDateAxis(XYPlot plot) { XYItemRenderer renderer = plot.getRenderer(); StandardXYToolTipGenerator generator; if (timeType.equalsIgnoreCase("Year")) generator = new StandardXYToolTipGenerator("{1} = {2}", new SimpleDateFormat("yyyy"), new DecimalFormat("0")); else if (timeType.equalsIgnoreCase("Day")) generator = new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT, new SimpleDateFormat("d-MMM-yy"), new DecimalFormat("#,##0.00")); else if (timeType.equalsIgnoreCase("Month")) generator = new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT, new SimpleDateFormat("MM-yy"), new DecimalFormat("#,##0.00")); else generator = new StandardXYToolTipGenerator("", DateFormat.getDateInstance(), new DecimalFormat("#,##0.00")); renderer.setBaseToolTipGenerator(generator); DateAxis domainAxis = new DateAxis("Time"); domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE); domainAxis.setLowerMargin(0.0); domainAxis.setUpperMargin(0.0); plot.setDomainAxis(domainAxis); //plot.setForegroundAlpha(0.5f); }
From source file:com.naryx.tagfusion.cfm.tag.awt.cfCHART.java
private XYPlot getXYPlot(List<cfCHARTSERIESData> series, String xAxisTitle, String yAxisTitle, String labelFormat, boolean bShowMarkers, int markerSize, boolean bShow3D, String tipStyle, String drillDownUrl, int xOffset, int yOffset, int yAxisUnits, String seriesPlacement, int height, int gridLines) throws cfmRunTimeException { // Create an XY plot XYPlot plot = new XYPlot(); ValueAxis domainAxis;//from w w w . j ava2s .co m if (series.get(0).getSeriesDataType() == cfCHARTSERIESData.XY_NUMERIC_SERIES) { if (bShow3D) domainAxis = new NumberAxis3D(xAxisTitle); else domainAxis = new NumberAxis(xAxisTitle); } else { domainAxis = new DateAxis(xAxisTitle); } plot.setDomainAxis(domainAxis); ValueAxis valueAxis; DateFormat dateFormat = null; NumberFormat numberFormat = null; if (labelFormat.equals("date")) { valueAxis = new DateAxis(yAxisTitle); dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); ((DateAxis) valueAxis).setDateFormatOverride(dateFormat); } else { if (bShow3D) valueAxis = new NumberAxis3D(yAxisTitle); else valueAxis = new NumberAxis(yAxisTitle); if (labelFormat.equals("currency")) { ((NumberAxis) valueAxis).setNumberFormatOverride(NumberFormat.getCurrencyInstance()); numberFormat = NumberFormat.getCurrencyInstance(); } else if (labelFormat.equals("percent")) { numberFormat = NumberFormat.getPercentInstance(); numberFormat.setMaximumFractionDigits(3); // without this change .11443 // would be displayed as 11% // instead of 11.443% ((NumberAxis) valueAxis).setNumberFormatOverride(numberFormat); } else { numberFormat = NumberFormat.getInstance(); } if (yAxisUnits != 0) ((NumberAxis) valueAxis).setTickUnit(new NumberTickUnit(yAxisUnits)); } plot.setRangeAxis(valueAxis); // Add a dataset and renderer for each series int barChartDatasetIndex = -1; int hBarChartDatasetIndex = -1; int num = 0; MinMaxData minMax = new MinMaxData(); for (int i = 0; i < series.size(); i++) { cfCHARTSERIESData seriesData = series.get(i); XYSeriesCollection dataset; if ((barChartDatasetIndex != -1) && (seriesData.getType().equals("bar"))) { dataset = (XYSeriesCollection) plot.getDataset(barChartDatasetIndex); addSeriesDataToDataset(seriesData, dataset, minMax); // Set the paint style for this series setPaintStyle(seriesData.getPaintStyle(), plot.getRenderer(barChartDatasetIndex), dataset.getSeriesCount() - 1, height); // Add the color list for this series to the custom color renderer CustomColorRenderer cr = (CustomColorRenderer) plot.getRenderer(barChartDatasetIndex); cr.addColors(getColorList(seriesData)); continue; } else if ((hBarChartDatasetIndex != -1) && (seriesData.getType().equals("horizontalbar"))) { dataset = (XYSeriesCollection) plot.getDataset(hBarChartDatasetIndex); addSeriesDataToDataset(seriesData, dataset, minMax); // Set the paint style for this series setPaintStyle(seriesData.getPaintStyle(), plot.getRenderer(hBarChartDatasetIndex), dataset.getSeriesCount() - 1, height); // Add the color list for this series to the custom color renderer CustomColorRenderer cr = (CustomColorRenderer) plot.getRenderer(hBarChartDatasetIndex); cr.addColors(getColorList(seriesData)); continue; } else { dataset = new XYSeriesCollection(); addSeriesDataToDataset(seriesData, dataset, minMax); } plot.setDataset(num, dataset); XYItemRenderer renderer = null; if (seriesData.getType().equals("bar")) { plot.setOrientation(PlotOrientation.VERTICAL); renderer = getXYBarRenderer(seriesPlacement, bShow3D, xOffset, yOffset, getColorList(seriesData)); ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BOTTOM_CENTER); renderer.setPositiveItemLabelPosition(position1); ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE6, TextAnchor.TOP_CENTER); renderer.setNegativeItemLabelPosition(position2); ((XYBarRenderer) renderer).setMargin(0.2); // The margin between each // category barChartDatasetIndex = num; } else if (seriesData.getType().equals("horizontalbar")) { plot.setOrientation(PlotOrientation.HORIZONTAL); plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT); renderer = getXYBarRenderer(seriesPlacement, bShow3D, xOffset, yOffset, getColorList(seriesData)); ItemLabelPosition position1 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.CENTER_LEFT); renderer.setPositiveItemLabelPosition(position1); ItemLabelPosition position2 = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE9, TextAnchor.CENTER_RIGHT); renderer.setNegativeItemLabelPosition(position2); ((XYBarRenderer) renderer).setMargin(0.2); // The margin between each // category hBarChartDatasetIndex = num; } else if (seriesData.getType().equals("line")) { renderer = new XYLineAndShapeRenderer(true, false); // Enable/Disable displaying of markers ((XYLineAndShapeRenderer) renderer).setShapesVisible(bShowMarkers); // Set the shape of the markers based on the markerSize value ((XYLineAndShapeRenderer) renderer).setShape(getMarker(seriesData.getMarkerStyle(), markerSize)); } else if (seriesData.getType().equals("area")) { renderer = new CustomXYAreaRenderer(); } else if (seriesData.getType().equals("step")) { renderer = new CustomXYStepRenderer(); } else if (seriesData.getType().equals("scatter")) { renderer = new XYLineAndShapeRenderer(false, true); // Set the shape of the markers based on the markerSize value ((XYLineAndShapeRenderer) renderer).setShape(getMarker(seriesData.getMarkerStyle(), markerSize)); } if (!tipStyle.equals("none")) { if (series.get(0).getSeriesDataType() == cfCHARTSERIESData.XY_DATE_SERIES) { renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{0}: {1}", DateFormat.getInstance(), DateFormat.getInstance())); } else { if (dateFormat != null) renderer.setBaseToolTipGenerator( new StandardXYToolTipGenerator("{0}: {2}", dateFormat, dateFormat)); else renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator("{0}: ({1}, {2})", numberFormat, NumberFormat.getInstance())); } } if (drillDownUrl != null) { if (dateFormat != null) renderer.setURLGenerator( new com.newatlanta.bluedragon.XYURLGenerator(drillDownUrl, dateFormat)); else renderer.setURLGenerator( new com.newatlanta.bluedragon.XYURLGenerator(drillDownUrl, numberFormat)); } if (seriesData.getSeriesColor() != null) renderer.setSeriesPaint(0, convertStringToColor(seriesData.getSeriesColor())); String dataLabelStyle = seriesData.getDataLabelStyle(); if (labelFormat.equals("date")) { if (dataLabelStyle.equals("none")) { renderer.setItemLabelsVisible(false); } else { setXYItemLabelsData(renderer, seriesData); if (dataLabelStyle.equals("value")) renderer.setItemLabelGenerator( new StandardXYItemLabelGenerator("{2}", dateFormat, dateFormat)); else if (dataLabelStyle.equals("rowlabel")) renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator("{0}", NumberFormat.getInstance(), NumberFormat.getInstance())); else if (dataLabelStyle.equals("columnlabel")) renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator("{1}", NumberFormat.getInstance(), NumberFormat.getInstance())); else if (dataLabelStyle.equals("pattern")) renderer.setItemLabelGenerator(new XYItemLabelGenerator("{2}", dateFormat, dateFormat)); else renderer.setItemLabelGenerator( new XYItemLabelGenerator(dataLabelStyle, dateFormat, dateFormat)); } } else { if (dataLabelStyle.equals("none")) { renderer.setItemLabelsVisible(false); } else { setXYItemLabelsData(renderer, seriesData); if (dataLabelStyle.equals("value")) { renderer.setItemLabelGenerator( new StandardXYItemLabelGenerator("{2}", numberFormat, numberFormat)); } else if (dataLabelStyle.equals("rowlabel")) { renderer.setItemLabelGenerator( new StandardXYItemLabelGenerator("{0}", numberFormat, numberFormat)); } else if (dataLabelStyle.equals("columnlabel")) { if (series.get(0).getSeriesDataType() == cfCHARTSERIESData.XY_DATE_SERIES) { renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator("{1}", SimpleDateFormat.getInstance(), NumberFormat.getInstance())); } else { renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator("{1}", NumberFormat.getInstance(), NumberFormat.getInstance())); } } else if (dataLabelStyle.equals("pattern")) { if (series.get(0).getSeriesDataType() == cfCHARTSERIESData.XY_DATE_SERIES) { renderer.setItemLabelGenerator(new XYItemLabelGenerator("{1} {2} ({3} of {4})", SimpleDateFormat.getInstance(), numberFormat)); } else { renderer.setItemLabelGenerator(new XYItemLabelGenerator("{1} {2} ({3} of {4})", NumberFormat.getInstance(), numberFormat)); } } else { renderer.setItemLabelGenerator( new XYItemLabelGenerator(dataLabelStyle, NumberFormat.getInstance(), numberFormat)); } } } // Add the renderer to the plot. // NOTE: this must be done before the setPaintStyle() call so the // DrawingSupplier object // will be set up properly for the generation of default colors. plot.setRenderer(num, renderer); // Set the paint style for this series (series 0) if (seriesData.getType().equals("bar") || seriesData.getType().equals("horizontalbar") || seriesData.getType().equals("area")) setPaintStyle(seriesData.getPaintStyle(), renderer, 0, height); num++; } // If gridLines was specified then we need to calculate the yAxisUnits if ((gridLines != -1) && (valueAxis instanceof NumberAxis)) { // Calculate the yAxisUnits we need to use to create the number of // gridLines yAxisUnits = calculateYAxisUnits(gridLines, minMax); // Set the yAxisUnits ((NumberAxis) valueAxis).setTickUnit(new NumberTickUnit(yAxisUnits)); } return plot; }
From source file:edu.jhuapl.graphs.jfreechart.JFreeChartTimeSeriesGraphSource.java
/** * Initializes the graph. This method generates the backing {@link JFreeChart} from the time series and graph * parameter data./* w ww.j a v a2s.c om*/ * * @throws GraphException if the initialization fails */ public void initialize() throws GraphException { String title = getParam(GraphSource.GRAPH_TITLE, String.class, DEFAULT_TITLE); String xLabel = getParam(GraphSource.GRAPH_X_LABEL, String.class, DEFAULT_DOMAIN_LABEL); String yLabel = getParam(GraphSource.GRAPH_Y_LABEL, String.class, DEFAULT_RANGE_LABEL); Shape graphShape = getParam(GraphSource.GRAPH_SHAPE, Shape.class, DEFAULT_GRAPH_SHAPE); Paint graphColor = getParam(GraphSource.GRAPH_COLOR, Paint.class, DEFAULT_GRAPH_COLOR); boolean legend = getParam(GraphSource.GRAPH_LEGEND, Boolean.class, DEFAULT_GRAPH_LEGEND); boolean graphToolTip = getParam(GraphSource.GRAPH_TOOL_TIP, Boolean.class, DEFAULT_GRAPH_TOOL_TIP); Stroke graphStroke = getParam(GraphSource.GRAPH_STROKE, Stroke.class, DEFAULT_GRAPH_STROKE); Font titleFont = getParam(GraphSource.GRAPH_FONT, Font.class, DEFAULT_GRAPH_TITLE_FONT); boolean graphBorder = getParam(GraphSource.GRAPH_BORDER, Boolean.class, DEFAULT_GRAPH_BORDER); boolean legendBorder = getParam(GraphSource.LEGEND_BORDER, Boolean.class, DEFAULT_LEGEND_BORDER); Double offset = getParam(GraphSource.AXIS_OFFSET, Double.class, DEFAULT_AXIS_OFFSET); checkSeriesType(data); @SuppressWarnings("unchecked") List<? extends TimeSeriesInterface> timeData = (List<? extends TimeSeriesInterface>) data; TimeSeriesCollection dataset = new TimeSeriesCollection(); int seriesCount = 1; for (TimeSeriesInterface series : timeData) { dataset.addSeries(buildTimeSeries(series, seriesCount)); seriesCount += 1; } // actually create the chart this.chart = ChartFactory.createTimeSeriesChart(title, xLabel, yLabel, dataset, false, graphToolTip, false); // start customizing it Paint backgroundColor = getParam(GraphSource.BACKGROUND_COLOR, Paint.class, DEFAULT_BACKGROUND_COLOR); Paint plotColor = getParam(JFreeChartTimeSeriesGraphSource.PLOT_COLOR, Paint.class, backgroundColor); Paint graphDomainGridlinePaint = getParam(GraphSource.GRAPH_DOMAIN_GRIDLINE_PAINT, Paint.class, backgroundColor); Paint graphRangeGridlinePaint = getParam(GraphSource.GRAPH_RANGE_GRIDLINE_PAINT, Paint.class, backgroundColor); this.chart.setBackgroundPaint(backgroundColor); XYPlot plot = chart.getXYPlot(); plot.setBackgroundPaint(plotColor); plot.setAxisOffset(new RectangleInsets(offset, offset, offset, offset)); plot.setDomainGridlinePaint(graphDomainGridlinePaint); plot.setRangeGridlinePaint(graphRangeGridlinePaint); if (graphBorder) { } else { plot.setOutlinePaint(null); } //Use a TextTitle to change the font of the graph title TextTitle title1 = new TextTitle(); title1.setText(title); title1.setFont(titleFont); chart.setTitle(title1); //Makes a wrapper for the legend to remove the border around it if (legend) { LegendTitle legend1 = new LegendTitle(chart.getPlot()); BlockContainer wrapper = new BlockContainer(new BorderArrangement()); if (legendBorder) { wrapper.setFrame(new BlockBorder(1, 1, 1, 1)); } else { wrapper.setFrame(new BlockBorder(0, 0, 0, 0)); } BlockContainer items = legend1.getItemContainer(); items.setPadding(2, 10, 5, 2); wrapper.add(items); legend1.setWrapper(wrapper); legend1.setPosition(RectangleEdge.BOTTOM); legend1.setHorizontalAlignment(HorizontalAlignment.CENTER); if (params.get(GraphSource.LEGEND_FONT) instanceof Font) { legend1.setItemFont(((Font) params.get(GraphSource.LEGEND_FONT))); } chart.addSubtitle(legend1); } boolean include0 = getParam(GraphSource.GRAPH_RANGE_INCLUDE_0, Boolean.class, true); NumberAxis numAxis = (NumberAxis) plot.getRangeAxis(); double rangeLower = getParam(GraphSource.GRAPH_RANGE_LOWER_BOUND, Double.class, numAxis.getLowerBound()); double rangeUpper = getParam(GraphSource.GRAPH_RANGE_UPPER_BOUND, Double.class, numAxis.getUpperBound()); boolean graphRangeIntegerTick = getParam(GraphSource.GRAPH_RANGE_INTEGER_TICK, Boolean.class, false); boolean graphRangeMinorTickVisible = getParam(GraphSource.GRAPH_RANGE_MINOR_TICK_VISIBLE, Boolean.class, true); if (include0) { rangeLower = 0; } numAxis.setRange(rangeLower, rangeUpper); if (graphRangeIntegerTick) { numAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); } numAxis.setMinorTickMarksVisible(graphRangeMinorTickVisible); setupFont(numAxis, GraphSource.GRAPH_Y_AXIS_FONT); if (params.get(GraphSource.GRAPH_Y_AXIS_LABEL_FONT) instanceof Font) { numAxis.setLabelFont(((Font) params.get(GraphSource.GRAPH_Y_AXIS_LABEL_FONT))); } TimeResolution minimumResolution = getMinimumResolution(timeData); DateFormat dateFormat = getParam(GraphSource.GRAPH_DATE_FORMATTER, DateFormat.class, new DefaultDateFormatFactory().getFormat(minimumResolution)); if (params.get(DATE_AXIS) instanceof DateAxis) { DateAxis dateAxis = (DateAxis) params.get(DATE_AXIS); dateAxis.setLabel(xLabel); plot.setDomainAxis(dateAxis); } DateAxis dateAxis = ((DateAxis) plot.getDomainAxis()); dateAxis.setDateFormatOverride(dateFormat); if (params.get(GraphSource.GRAPH_X_AXIS_LABEL_FONT) instanceof Font) { dateAxis.setLabelFont(((Font) params.get(GraphSource.GRAPH_X_AXIS_LABEL_FONT))); } int minTick = getParam(GraphSource.GRAPH_MIN_DOMAIN_TICK, Integer.class, 1); if (minTick <= 0) { minTick = 1; } dateAxis.setTickUnit(getDateTickUnit(minimumResolution, minTick), false, false); //dateAxis.setMinorTickMarksVisible(true); //dateAxis.setMinorTickCount(7); dateAxis.setMinorTickMarkOutsideLength(2); Integer minorTick = getParam(GraphSource.GRAPH_MINOR_TICKS, Integer.class, null); if (minorTick != null) { int minorVal = minorTick; if (minorVal > 0) { dateAxis.setMinorTickCount(minorVal); } } setupFont(dateAxis, GraphSource.GRAPH_X_AXIS_FONT); //double lowerMargin = getParam(DOMAIN_AXIS_LOWER_MARGIN, Double.class, DEFAULT_DOMAIN_AXIS_LOWER_MARGIN); double lowerMargin = getParam(DOMAIN_AXIS_LOWER_MARGIN, Double.class, DEFAULT_DOMAIN_AXIS_LOWER_MARGIN); dateAxis.setLowerMargin(lowerMargin); //double upperMargin = getParam(DOMAIN_AXIS_UPPER_MARGIN, Double.class, DEFAULT_DOMAIN_AXIS_UPPER_MARGIN); double upperMargin = getParam(DOMAIN_AXIS_UPPER_MARGIN, Double.class, DEFAULT_DOMAIN_AXIS_UPPER_MARGIN); dateAxis.setUpperMargin(upperMargin); Date domainLower = getParam(GraphSource.GRAPH_DOMAIN_LOWER_BOUND, Date.class, dateAxis.getMinimumDate()); Date domainUpper = getParam(GraphSource.GRAPH_DOMAIN_UPPER_BOUND, Date.class, dateAxis.getMaximumDate()); dateAxis.setRange(domainLower, domainUpper); // depending on the domain axis range, display either 1 tick per day, week, month or year TickUnits standardUnits = new TickUnits(); standardUnits.add(new DateTickUnit(DateTickUnitType.DAY, 1)); standardUnits.add(new DateTickUnit(DateTickUnitType.DAY, 7)); standardUnits.add(new DateTickUnit(DateTickUnitType.MONTH, 1)); standardUnits.add(new DateTickUnit(DateTickUnitType.YEAR, 1)); dateAxis.setStandardTickUnits(standardUnits); TimeSeriesRenderer renderer = new TimeSeriesRenderer(dataset); setupRenderer(renderer, graphColor, graphShape, graphStroke); renderer.setBaseFillPaint(Color.BLACK); renderer.setSeriesOutlinePaint(0, Color.WHITE); //renderer.setUseOutlinePaint(true); plot.setRenderer(renderer); this.initialized = true; }
From source file:org.esa.snap.rcp.statistics.ScatterPlotPanel.java
private void createUI() { final XYPlot plot = getPlot(); plot.setAxisOffset(new RectangleInsets(5, 5, 5, 5)); plot.setNoDataMessage(NO_DATA_MESSAGE); int confidenceDSIndex = 0; int regressionDSIndex = 1; int scatterpointsDSIndex = 2; plot.setDataset(confidenceDSIndex, acceptableDeviationDataset); plot.setDataset(regressionDSIndex, regressionDataset); plot.setDataset(scatterpointsDSIndex, scatterpointsDataset); plot.addAnnotation(r2Annotation); final DeviationRenderer identityRenderer = new DeviationRenderer(true, false); identityRenderer.setSeriesPaint(0, StatisticChartStyling.SAMPLE_DATA_PAINT); identityRenderer.setSeriesFillPaint(0, StatisticChartStyling.SAMPLE_DATA_FILL_PAINT); plot.setRenderer(confidenceDSIndex, identityRenderer); final DeviationRenderer regressionRenderer = new DeviationRenderer(true, false); regressionRenderer.setSeriesPaint(0, StatisticChartStyling.REGRESSION_DATA_PAINT); regressionRenderer.setSeriesFillPaint(0, StatisticChartStyling.REGRESSION_DATA_FILL_PAINT); plot.setRenderer(regressionDSIndex, regressionRenderer); final XYErrorRenderer scatterPointsRenderer = new XYErrorRenderer(); scatterPointsRenderer.setDrawXError(true); scatterPointsRenderer.setErrorStroke(new BasicStroke(1)); scatterPointsRenderer.setErrorPaint(StatisticChartStyling.CORRELATIVE_POINT_OUTLINE_PAINT); scatterPointsRenderer.setSeriesShape(0, StatisticChartStyling.CORRELATIVE_POINT_SHAPE); scatterPointsRenderer.setSeriesOutlinePaint(0, StatisticChartStyling.CORRELATIVE_POINT_OUTLINE_PAINT); scatterPointsRenderer.setSeriesFillPaint(0, StatisticChartStyling.CORRELATIVE_POINT_FILL_PAINT); scatterPointsRenderer.setSeriesLinesVisible(0, false); scatterPointsRenderer.setSeriesShapesVisible(0, true); scatterPointsRenderer.setSeriesOutlineStroke(0, new BasicStroke(1.0f)); scatterPointsRenderer.setSeriesToolTipGenerator(0, (dataset, series, item) -> { final XYIntervalSeriesCollection collection = (XYIntervalSeriesCollection) dataset; final Comparable key = collection.getSeriesKey(series); final double xValue = collection.getXValue(series, item); final double endYValue = collection.getEndYValue(series, item); final double yValue = collection.getYValue(series, item); return String.format("%s: mean = %6.2f, sigma = %6.2f | %s: value = %6.2f", getRasterName(), yValue, endYValue - yValue, key, xValue); });/*from w ww .j a v a 2 s .co m*/ plot.setRenderer(scatterpointsDSIndex, scatterPointsRenderer); final boolean autoRangeIncludesZero = false; final boolean xLog = scatterPlotModel.xAxisLogScaled; final boolean yLog = scatterPlotModel.yAxisLogScaled; plot.setDomainAxis( StatisticChartStyling.updateScalingOfAxis(xLog, plot.getDomainAxis(), autoRangeIncludesZero)); plot.setRangeAxis( StatisticChartStyling.updateScalingOfAxis(yLog, plot.getRangeAxis(), autoRangeIncludesZero)); createUI(createChartPanel(chart), createInputParameterPanel(), bindingContext); plot.getDomainAxis().addChangeListener(domainAxisChangeListener); scatterPlotDisplay.setMouseWheelEnabled(true); scatterPlotDisplay.setMouseZoomable(true); }