List of usage examples for org.jfree.chart.axis NumberAxis setAutoRangeIncludesZero
public void setAutoRangeIncludesZero(boolean flag)
From source file:AltiConsole.AltiConsoleMainScreen.java
/** * Constructs main screen of the application. * //w ww .ja v a 2 s . c o m * @param title * the frame title. */ public AltiConsoleMainScreen(final String title) { super(title); trans = Application.getTranslator(); // //////// Menu code starts her ////////////// // File fileMenu = new JMenu(); fileMenu.setText(trans.get("AltiConsoleMainScreen.File")); // Load data loadDataMenuItem = new JMenuItem(); loadDataMenuItem.setText(trans.get("AltiConsoleMainScreen.RetrieveFlightData")); loadDataMenuItem.setActionCommand("RETRIEVE_FLIGHT"); loadDataMenuItem.addActionListener(this); eraseAllDataMenuItem = new JMenuItem(); eraseAllDataMenuItem.setText(trans.get("AltiConsoleMainScreen.EraseFlightData")); eraseAllDataMenuItem.setActionCommand("ERASE_FLIGHT"); eraseAllDataMenuItem.addActionListener(this); // Save as saveASMenuItem = new JMenuItem(); saveASMenuItem.setText(trans.get("AltiConsoleMainScreen.saveFlightData")); saveASMenuItem.setActionCommand("SAVE_FLIGHT"); saveASMenuItem.addActionListener(this); // Exit exitMenuItem = new JMenuItem(); exitMenuItem.setText(trans.get("AltiConsoleMainScreen.Exit")); exitMenuItem.setActionCommand("EXIT"); exitMenuItem.addActionListener(this); fileMenu.add(saveASMenuItem); fileMenu.add(loadDataMenuItem); fileMenu.add(eraseAllDataMenuItem); fileMenu.add(exitMenuItem); // Option menu optionMenu = new JMenu(trans.get("AltiConsoleMainScreen.Option")); preferencesMenuItem = new JMenuItem(trans.get("AltiConsoleMainScreen.Preferences")); preferencesMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("pref\n"); Preferences.showPreferences(AltiConsoleMainScreen.this); //LicenseDialog.showPreferences(AltiConsoleMainScreen.this); System.out.println("change units\n"); String Units; System.out.println(UserPref.getAppUnits()); if (Utils.equals(UserPref.getAppUnits(), "Unit.Metrics")) Units = trans.get("Unit.Metrics"); else Units = trans.get("Unit.Imperial"); chart.getXYPlot().getRangeAxis() .setLabel(trans.get("AltiConsoleMainScreen.altitude") + " (" + Units + ")"); if (Serial.getConnected()) { RetrievingFlight(); } } }); optionMenu.add(preferencesMenuItem); // Configuration menu altiConfigMenu = new JMenu(trans.get("AltiConsoleMainScreen.ConfigAltimeter")); retrieveAltiConfigMenuItem = new JMenuItem(trans.get("AltiConsoleMainScreen.RetrieveAltiConfig")); retrieveAltiConfigMenuItem.setActionCommand("RETRIEVE_ALTI_CFG"); retrieveAltiConfigMenuItem.addActionListener(this); altiConfigMenu.add(retrieveAltiConfigMenuItem); uploadFirmwareMenuItem = new JMenuItem(trans.get("AltiConsoleMainScreen.UploadFirmware")); uploadFirmwareMenuItem.setActionCommand("UPLOAD_FIRMWARE"); uploadFirmwareMenuItem.addActionListener(this); altiConfigMenu.add(uploadFirmwareMenuItem); // Help helpMenu = new JMenu(trans.get("AltiConsoleMainScreen.Help")); jJMenuBar = new JMenuBar(); // Manual onLineHelpMenuItem = new JMenuItem(trans.get("AltiConsoleMainScreen.onLineHelp")); onLineHelpMenuItem.setActionCommand("ON_LINE_HELP"); onLineHelpMenuItem.addActionListener(this); // license licenseMenuItem = new JMenuItem(trans.get("AltiConsoleMainScreen.license")); licenseMenuItem.setActionCommand("LICENSE"); licenseMenuItem.addActionListener(this); // AboutScreen aboutMenuItem = new JMenuItem(); aboutMenuItem.setText(trans.get("AltiConsoleMainScreen.About")); aboutMenuItem.setActionCommand("ABOUT"); aboutMenuItem.addActionListener(this); helpMenu.add(onLineHelpMenuItem); helpMenu.add(licenseMenuItem); helpMenu.add(aboutMenuItem); jJMenuBar.add(fileMenu); jJMenuBar.add(optionMenu); jJMenuBar.add(altiConfigMenu); jJMenuBar.add(helpMenu); this.setJMenuBar(jJMenuBar); // ///// end of Menu code // Button retrieveFlights = new JButton(); retrieveFlights.setText(trans.get("AltiConsoleMainScreen.RetrieveFlights")); retrieveFlights.setActionCommand("RETRIEVE_FLIGHT"); retrieveFlights.addActionListener(this); retrieveFlights.setToolTipText(trans.get("AltiConsoleMainScreen.ttipRetrieveFlight")); // combo serial rate String[] serialRateStrings = { "300", "1200", "2400", "4800", "9600", "14400", "19200", "28800", "38400", "57600", "115200" }; serialRatesLabel = new JLabel(trans.get("AltiConsoleMainScreen.comPortSpeed") + " "); serialRates = new JComboBox(); System.out.println(UserPref.getDefComSpeed() + "\n"); for (int i = 0; i < serialRateStrings.length; i++) { serialRates.addItem(serialRateStrings[i]); if (Utils.equals(UserPref.getDefComSpeed(), serialRateStrings[i])) { serialRates.setSelectedIndex(i); } } serialRates.setToolTipText(trans.get("AltiConsoleMainScreen.ttipChoosePortSpeed")); comPortsLabel = new JLabel(trans.get("AltiConsoleMainScreen.port") + " "); comPorts = new JComboBox(); comPorts.setActionCommand("comPorts"); comPorts.addActionListener(this); comPorts.setToolTipText(trans.get("AltiConsoleMainScreen.ttipChooseAltiport")); listData = new DefaultListModel(); flightList = new JXList(listData); flightList.addListSelectionListener(new ValueReporter()); JPanel TopPanelLeft = new JPanel(); TopPanelLeft.setLayout(new BorderLayout()); TopPanelLeft.add(comPortsLabel, BorderLayout.WEST); TopPanelLeft.add(comPorts, BorderLayout.EAST); JPanel TopPanelMiddle = new JPanel(); TopPanelMiddle.setLayout(new BorderLayout()); TopPanelMiddle.add(retrieveFlights, BorderLayout.WEST); JPanel TopPanelRight = new JPanel(); TopPanelRight.setLayout(new BorderLayout()); TopPanelRight.add(serialRatesLabel, BorderLayout.WEST); TopPanelRight.add(serialRates, BorderLayout.EAST); JPanel TopPanel = new JPanel(); TopPanel.setLayout(new BorderLayout()); TopPanel.add(TopPanelRight, BorderLayout.EAST); TopPanel.add(TopPanelMiddle, BorderLayout.CENTER); TopPanel.add(TopPanelLeft, BorderLayout.WEST); JPanel MiddlePanel = new JPanel(); MiddlePanel.setLayout(new BorderLayout()); MiddlePanel.add(TopPanel, BorderLayout.NORTH); MiddlePanel.add(flightList, BorderLayout.WEST); String Units; if (Utils.equals(UserPref.getAppUnits(), "Unit.Metrics")) Units = trans.get("Unit.Metrics"); else Units = trans.get("Unit.Imperial"); chart = ChartFactory.createXYLineChart(trans.get("AltiConsoleMainScreen.Title"), trans.get("AltiConsoleMainScreen.time"), trans.get("AltiConsoleMainScreen.altitude") + " (" + Units + ")", null); chart.setBackgroundPaint(Color.white); System.out.println(chart.getSubtitle(0)); this.plot = chart.getXYPlot(); this.plot.setBackgroundPaint(Color.lightGray); this.plot.setDomainGridlinePaint(Color.white); this.plot.setRangeGridlinePaint(Color.white); final ValueAxis axis = this.plot.getDomainAxis(); axis.setAutoRange(true); final NumberAxis rangeAxis2 = new NumberAxis("Range Axis 2"); rangeAxis2.setAutoRangeIncludesZero(false); final ChartPanel chartPanel = new ChartPanel(chart); MiddlePanel.add(chartPanel, BorderLayout.CENTER); JPanel InfoPanel = new JPanel(new MigLayout("fill")); InfoPanel.add(new JLabel(trans.get("AltiConsoleMainScreen.ApogeeAltitude")), "gapright para"); apogeeAltitudeLabel = new JLabel(); InfoPanel.add(apogeeAltitudeLabel, "growx"); InfoPanel.add(new JLabel(trans.get("AltiConsoleMainScreen.MainAltitude")), "gapright para"); mainAltitudeLabel = new JLabel(); InfoPanel.add(mainAltitudeLabel, "growx"); flightNbrLabel = new JLabel(); InfoPanel.add(new JLabel(trans.get("AltiConsoleMainScreen.NbrOfPoint")), "growx"); nbrPointLabel = new JLabel(); InfoPanel.add(nbrPointLabel, "wrap rel,growx"); txtLog = new JTextArea(5, 70); txtLog.setEditable(false); txtLog.setAutoscrolls(true); scrollPane = new JScrollPane(txtLog); scrollPane.setAutoscrolls(true); // BottomPanel.add(scrollPane, BorderLayout.WEST); InfoPanel.add(scrollPane, "span"); // MiddlePanel.add(BottomPanel, BorderLayout.SOUTH); MiddlePanel.add(InfoPanel, BorderLayout.SOUTH); setContentPane(MiddlePanel); try { try { Serial = new AltimeterSerial(this); Serial.searchForPorts(); } catch (UnsatisfiedLinkError e) { System.out.println("USB Library rxtxSerial.dll Not Found"); System.out.println("Exception:" + e.toString() + ":" + e.getMessage()); System.out.println(e.toString()); JOptionPane.showMessageDialog(null, "You must copy the appropriate rxtxSerial.dll \n " + "to your local 32 bit or 64 bitjava JRE installation\n\n" + " .../arduino-1.0.1-windows/arduino-1.0.1/rxtxSerial.dll\n" + "to\n C:/Program Files (x86)/Java/jre7/bin/rxtxSerial.dll\n" + "also right click Properties->Unblock", trans.get("AltiConsoleMainScreen.InstallationProblem"), JOptionPane.WARNING_MESSAGE); } } catch (NoClassDefFoundError e) { System.out.println("Missing RXTXcomm.jar in java installation"); System.out.println("Exception:" + e.toString() + ":" + e.getMessage()); System.out.println(e.toString()); JOptionPane.showMessageDialog(null, "You must copy RXTXcomm.jar from the Arduino software\n " + "to your local 32 bit java JRE installation\n\n" + " .../arduino-1.0.1-windows/arduino-1.0.1/lib/RXTXcomm.jar\n" + "to\n C:/Program Files (x86)/Java/jre7/lib/ext/RXTXcomm.jar\n" + "also right click Properties->Unblock", trans.get("AltiConsoleMainScreen.InstallationProblem"), JOptionPane.WARNING_MESSAGE); } }
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. //from w w w . ja v a 2 s .c om @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.gwaspi.gui.reports.ManhattanPlotZoom.java
private JFreeChart createChart(XYDataset dataset, ChromosomeKey chr) { JFreeChart chart = ChartFactory.createScatterPlot(null, "", "P value", dataset, PlotOrientation.VERTICAL, true, false, false);/* w w w.jav a 2s . c om*/ XYPlot plot = (XYPlot) chart.getPlot(); plot.setNoDataMessage("NO DATA"); plot.setDomainZeroBaselineVisible(true); plot.setRangeZeroBaselineVisible(true); // CHART BACKGROUD COLOR chart.setBackgroundPaint(Color.getHSBColor(0.1f, 0.1f, 1.0f)); // Hue, saturation, brightness plot.setBackgroundPaint(manhattan_back); // Hue, saturation, brightness 9 // GRIDLINES plot.setDomainGridlineStroke(new BasicStroke(0.0f)); plot.setDomainMinorGridlineStroke(new BasicStroke(0.0f)); plot.setDomainGridlinePaint(manhattan_back.darker().darker()); // Hue, saturation, brightness 7 plot.setDomainMinorGridlinePaint(manhattan_back); // Hue, saturation, brightness 9 plot.setRangeGridlineStroke(new BasicStroke(0.0f)); plot.setRangeMinorGridlineStroke(new BasicStroke(0.0f)); plot.setRangeGridlinePaint(manhattan_back.darker().darker()); // Hue, saturation, brightness 7 plot.setRangeMinorGridlinePaint(manhattan_back.darker()); // Hue, saturation, brightness 8 plot.setDomainMinorGridlinesVisible(true); plot.setRangeMinorGridlinesVisible(true); // DOTS RENDERER XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); renderer.setSeriesPaint(0, manhattan_dot); // renderer.setSeriesOutlinePaint(0, Color.DARK_GRAY); // renderer.setUseOutlinePaint(true); // Set dot shape of the currently appended Series renderer.setSeriesShape(0, new Rectangle2D.Double(0.0, 0.0, 2, 2)); renderer.setSeriesVisibleInLegend(0, false); NumberAxis positionAxis = (NumberAxis) plot.getDomainAxis(); // domainAxis.setAutoRangeIncludesZero(false); // domainAxis.setTickMarkInsideLength(2.0f); // domainAxis.setTickMarkOutsideLength(2.0f); // domainAxis.setMinorTickCount(2); // domainAxis.setMinorTickMarksVisible(true); positionAxis.setLabelAngle(1.0); positionAxis.setAutoRangeIncludesZero(false); positionAxis.setAxisLineVisible(true); positionAxis.setTickLabelsVisible(true); positionAxis.setTickMarksVisible(true); // ADD INVERSE LOG(10) Y AXIS LogAxis logPAxis = new LogAxis("P value"); logPAxis.setBase(10); logPAxis.setInverted(true); logPAxis.setNumberFormatOverride(GenericReportGenerator.FORMAT_P_VALUE); logPAxis.setTickMarkOutsideLength(2.0f); logPAxis.setMinorTickCount(2); logPAxis.setMinorTickMarksVisible(true); logPAxis.setAxisLineVisible(true); logPAxis.setUpperMargin(0); TickUnitSource units = NumberAxis.createIntegerTickUnits(); logPAxis.setStandardTickUnits(units); plot.setRangeAxis(0, logPAxis); // Add significance Threshold to subplot //threshold = 0.5/rdMatrixMetadata.getMarkerSetSize(); // (0.05/10? SNPs => 5*10-?) final Marker thresholdLine = new ValueMarker(threshold); thresholdLine.setPaint(Color.red); // Add legend to threshold thresholdLine.setLabel("P = " + GenericReportGenerator.FORMAT_P_VALUE.format(threshold)); thresholdLine.setLabelAnchor(RectangleAnchor.TOP_RIGHT); thresholdLine.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT); plot.addRangeMarker(thresholdLine); // Marker label if below threshold XYItemRenderer lblRenderer = plot.getRenderer(); // THRESHOLD AND SELECTED LABEL GENERATOR MySeriesItemLabelGenerator lblGenerator = new MySeriesItemLabelGenerator(threshold, chr); lblRenderer.setSeriesItemLabelGenerator(0, lblGenerator); lblRenderer.setSeriesItemLabelFont(0, new Font("SansSerif", Font.PLAIN, 12)); lblRenderer.setSeriesPositiveItemLabelPosition(0, new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.TOP_LEFT, TextAnchor.BOTTOM_LEFT, Math.PI / 4.0)); // TOOLTIP GENERATOR MyXYToolTipGenerator tooltipGenerator = new MyXYToolTipGenerator(chr); lblRenderer.setBaseToolTipGenerator(tooltipGenerator); lblRenderer.setSeriesItemLabelsVisible(0, true); return chart; }
From source file:net.sf.maltcms.chromaui.charts.Chromatogram1DChartProvider.java
/** * * @param dataset//from w w w . j a v a2s . c o m * @param tooltipGenerator * @param minRange * @param maxRange * @param useRT * @return */ public XYPlot provide1DCoPlot(XYZDataset dataset, SelectionAwareXYTooltipGenerator tooltipGenerator, double minRange, double maxRange, boolean useRT) { XYBlockRenderer xyb = new XYBlockRenderer(); GradientPaintScale ps = new GradientPaintScale(ImageTools.createSampleTable(256), minRange, maxRange, ImageTools.rampToColorArray(new ColorRampReader().readColorRamp("res/colorRamps/bcgyr.csv"))); xyb.setPaintScale(ps); final String[] colnames = new String[dataset.getSeriesCount()]; for (int i = 0; i < dataset.getSeriesCount(); i++) { colnames[i] = "" + dataset.getSeriesKey(i);//StringTools.removeFileExt(fragments.get(i).getName()); } NumberAxis na = null; if (useRT) { na = new NumberAxis("time [s]"); na.setAutoRangeIncludesZero(false); na.setLowerMargin(0); na.setUpperMargin(0); } else { na = new NumberAxis("scan index"); } // na.setVerticalTickLabels(true); XYPlot xyp = new XYPlot(dataset, na, new SymbolAxis("chromatogram", colnames), xyb); //xyb.setBlockWidth(1); xyp.setBackgroundPaint(ps.getPaint(ps.getLowerBound())); tooltipGenerator.setXYToolTipGenerator(new XYZToolTipGenerator() { @Override public String generateToolTip(XYZDataset xyzd, int i, int i1) { return colnames[xyzd.getY(i, i1).intValue()] + " @" + xyzd.getXValue(i, i1) + " = " + xyzd.getZValue(i, i1); } @Override public String generateToolTip(XYDataset xyd, int i, int i1) { if (xyd instanceof XYZDataset) { return generateToolTip((XYZDataset) xyd, i, i1); } return colnames[xyd.getY(i, i1).intValue()] + ":" + xyd.getXValue(i, i1); } }); xyb.setBaseToolTipGenerator(tooltipGenerator); return xyp; }
From source file:org.ramadda.data.services.PointFormHandler.java
/** * make the jfreechart for the waveform// w ww . j av a 2 s .c o m * * @param request the request * @param waveform the waveform * @param dataset the dataset * * @return chart */ private static JFreeChart createWaveformChart(Request request, Waveform waveform, XYDataset dataset) { JFreeChart chart = ChartFactory.createXYLineChart("", // chart title "", // x axis label "", // y axis label dataset, // data PlotOrientation.HORIZONTAL, false, // include legend false, // tooltips false // urls ); chart.setBackgroundPaint(Color.white); XYPlot plot = (XYPlot) chart.getPlot(); plot.setBackgroundPaint(Color.lightGray); // chart.getLegend().setVisible(false); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis(); rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); rangeAxis.setAutoRange(false); float[] range = waveform.getRange(); rangeAxis.setRange(new org.jfree.data.Range(range[0], range[1])); if (request.defined(ARG_WAVEFORM_AXIS_HIGH)) { domainAxis.setRange(new org.jfree.data.Range(request.get(ARG_WAVEFORM_AXIS_LOW, 0.0), request.get(ARG_WAVEFORM_AXIS_HIGH, 1000.0))); } domainAxis.setAutoRange(true); domainAxis.setAutoRangeIncludesZero(false); // domainAxis.setVisible(false); // rangeAxis.setFixedDimension(20); // plot.setInsets(new RectangleInsets(0, 0, 0, 0)); // plot.setAxisOffset(new RectangleInsets(5, 0, 5, 0)); return chart; }
From source file:org.mwc.debrief.track_shift.views.BaseStackedDotsView.java
/** * method to create a working plot (to contain our data) * /*from w ww. j av a 2s. c om*/ * @return the chart, in it's own panel */ @SuppressWarnings("deprecation") protected void createStackedPlot() { // first create the x (time) axis final SimpleDateFormat _df = new SimpleDateFormat("HHmm:ss"); _df.setTimeZone(TimeZone.getTimeZone("GMT")); final DateAxis xAxis = new CachedTickDateAxis(""); xAxis.setDateFormatOverride(_df); Font tickLabelFont = new Font("Courier", Font.PLAIN, 13); xAxis.setTickLabelFont(tickLabelFont); xAxis.setTickLabelPaint(Color.BLACK); xAxis.setStandardTickUnits(DateAxisEditor.createStandardDateTickUnitsAsTickUnits()); xAxis.setAutoTickUnitSelection(true); // create the special stepper plot _dotPlot = new XYPlot(); NumberAxis errorAxis = new NumberAxis("Error (" + getUnits() + ")"); Font axisLabelFont = new Font("Courier", Font.PLAIN, 16); errorAxis.setLabelFont(axisLabelFont); errorAxis.setTickLabelFont(tickLabelFont); _dotPlot.setRangeAxis(errorAxis); _dotPlot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT); _dotPlot.setRenderer(new ColourStandardXYItemRenderer(null, null, _dotPlot)); _dotPlot.setRangeGridlinePaint(Color.LIGHT_GRAY); _dotPlot.setRangeGridlineStroke(new BasicStroke(2)); _dotPlot.setDomainGridlinePaint(Color.LIGHT_GRAY); _dotPlot.setDomainGridlineStroke(new BasicStroke(2)); // now try to do add a zero marker on the error bar final Paint thePaint = Color.DARK_GRAY; final Stroke theStroke = new BasicStroke(3); final ValueMarker zeroMarker = new ValueMarker(0.0, thePaint, theStroke); _dotPlot.addRangeMarker(zeroMarker); _linePlot = new XYPlot(); final NumberAxis absBrgAxis = new NumberAxis("Absolute (" + getUnits() + ")"); absBrgAxis.setLabelFont(axisLabelFont); absBrgAxis.setTickLabelFont(tickLabelFont); _linePlot.setRangeAxis(absBrgAxis); absBrgAxis.setAutoRangeIncludesZero(false); _linePlot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT); final DefaultXYItemRenderer lineRend = new ColourStandardXYItemRenderer(null, null, _linePlot); lineRend.setPaint(Color.DARK_GRAY); _linePlot.setRenderer(lineRend); _linePlot.setDomainCrosshairVisible(true); _linePlot.setRangeCrosshairVisible(true); _linePlot.setDomainCrosshairPaint(Color.GRAY); _linePlot.setRangeCrosshairPaint(Color.GRAY); _linePlot.setDomainCrosshairStroke(new BasicStroke(3.0f)); _linePlot.setRangeCrosshairStroke(new BasicStroke(3.0f)); _linePlot.setRangeGridlinePaint(Color.LIGHT_GRAY); _linePlot.setRangeGridlineStroke(new BasicStroke(2)); _linePlot.setDomainGridlinePaint(Color.LIGHT_GRAY); _linePlot.setDomainGridlineStroke(new BasicStroke(2)); // and the plot object to display the cross hair value final XYTextAnnotation annot = new XYTextAnnotation("-----", 2, 2); annot.setTextAnchor(TextAnchor.TOP_LEFT); Font annotationFont = new Font("Courier", Font.BOLD, 16); annot.setFont(annotationFont); annot.setPaint(Color.DARK_GRAY); annot.setBackgroundPaint(Color.white); _linePlot.addAnnotation(annot); // give them a high contrast backdrop _dotPlot.setBackgroundPaint(Color.white); _linePlot.setBackgroundPaint(Color.white); // set the y axes to autocalculate _dotPlot.getRangeAxis().setAutoRange(true); _linePlot.getRangeAxis().setAutoRange(true); _combined = new CombinedDomainXYPlot(xAxis); _combined.add(_linePlot); _combined.add(_dotPlot); _combined.setOrientation(PlotOrientation.HORIZONTAL); // put the plot into a chart _myChart = new JFreeChart(null, null, _combined, true); final LegendItemSource[] sources = { _linePlot }; _myChart.getLegend().setSources(sources); _myChart.addProgressListener(new ChartProgressListener() { public void chartProgress(final ChartProgressEvent cpe) { if (cpe.getType() != ChartProgressEvent.DRAWING_FINISHED) return; // is hte line plot visible? if (!_showLinePlot.isChecked()) return; // double-check our label is still in the right place final double xVal = _linePlot.getRangeAxis().getLowerBound(); final double yVal = _linePlot.getDomainAxis().getUpperBound(); boolean annotChanged = false; if (annot.getX() != yVal) { annot.setX(yVal); annotChanged = true; } if (annot.getY() != xVal) { annot.setY(xVal); annotChanged = true; } // and write the text final String numA = MWC.Utilities.TextFormatting.GeneralFormat .formatOneDecimalPlace(_linePlot.getRangeCrosshairValue()); final Date newDate = new Date((long) _linePlot.getDomainCrosshairValue()); final SimpleDateFormat _df = new SimpleDateFormat("HHmm:ss"); _df.setTimeZone(TimeZone.getTimeZone("GMT")); final String dateVal = _df.format(newDate); final String theMessage = " [" + dateVal + "," + numA + "]"; if (!theMessage.equals(annot.getText())) { annot.setText(theMessage); annotChanged = true; } if (annotChanged) { _linePlot.removeAnnotation(annot); _linePlot.addAnnotation(annot); } } }); // and insert into the panel _holder.setChart(_myChart); // do a little tidying to reflect the memento settings if (!_showLinePlot.isChecked()) _combined.remove(_linePlot); if (!_showDotPlot.isChecked() && _showLinePlot.isChecked()) _combined.remove(_dotPlot); }
From source file:net.sf.maltcms.chromaui.charts.Chromatogram1DChartProvider.java
/** * * @param fragments/*from w w w . j a v a 2s . c om*/ * @param ticvar * @param useRT * @return */ public XYPlot provide1DCoPlot(List<IFileFragment> fragments, String ticvar, boolean useRT) { final String satVar = "scan_acquisition_time"; DefaultXYZDataset cd = new DefaultXYZDataset(); int rowIdx = 0; double min = 0; double max = 1; double minRT = Double.POSITIVE_INFINITY; double maxRT = Double.NEGATIVE_INFINITY; int y = 0; for (IFileFragment f : fragments) { double[] domainValues = null; if (useRT) { domainValues = (double[]) f.getChild(satVar).getArray().get1DJavaArray(double.class); } else { domainValues = (double[]) f.getChild("scan_index").getArray().get1DJavaArray(double.class); } double[] tic = (double[]) f.getChild(ticvar).getArray().get1DJavaArray(double.class); double maxtic = MathTools.max(tic); double mintic = MathTools.min(tic); double[][] values = new double[3][tic.length]; for (int i = 0; i < tic.length; i++) { values[0][i] = domainValues[i]; values[1][i] = y; values[2][i] = Math.sqrt((tic[i] - mintic) / (maxtic - mintic)); } y++; cd.addSeries(f.getName(), values); } // ArrayDouble.D1 a = new ArrayDouble.D1(npoints); // int offset = 0; // for (IFileFragment f : t) { // Array tic = f.getChild(ticvar).getArray(); // int len = tic.getShape()[0]; // Array.arraycopy(tic, 0, a, offset, len); // offset += len; // } // histogram with fixed binsize // fill intensities into adequate bin, raise count in bin by one // afterwards, relative frequency within a bin gives a normalization // coefficient XYBlockRenderer xyb = new XYBlockRenderer(); GradientPaintScale ps = new GradientPaintScale(ImageTools.createSampleTable(256), min, max, ImageTools.rampToColorArray(new ColorRampReader().readColorRamp("res/colorRamps/bcgyr.csv"))); xyb.setPaintScale(ps); final String[] colnames = new String[fragments.size()]; for (int i = 0; i < colnames.length; i++) { colnames[i] = StringTools.removeFileExt(fragments.get(i).getName()); } NumberAxis na = null; if (useRT) { na = new NumberAxis("time [s]"); na.setAutoRangeIncludesZero(false); na.setLowerMargin(0); na.setUpperMargin(0); } else { na = new NumberAxis("scan index"); } // na.setVerticalTickLabels(true); XYPlot xyp = new XYPlot(cd, na, new SymbolAxis("chromatogram", colnames), xyb); xyb.setBlockWidth(1); xyp.setBackgroundPaint(Color.BLACK); xyb.setBaseToolTipGenerator(new XYZToolTipGenerator() { @Override public String generateToolTip(XYZDataset xyzd, int i, int i1) { return colnames[xyzd.getY(i, i1).intValue()] + " @" + xyzd.getXValue(i, i1) + " = " + xyzd.getZValue(i, i1); } @Override public String generateToolTip(XYDataset xyd, int i, int i1) { if (xyd instanceof XYZDataset) { return generateToolTip((XYZDataset) xyd, i, i1); } return colnames[xyd.getY(i, i1).intValue()] + ":" + xyd.getXValue(i, i1); } }); return xyp; }
From source file:org.pentaho.chart.plugin.jfreechart.JFreeChartFactoryEngine.java
private void initXYPlot(JFreeChart chart, ChartModel chartModel) { initPlot(chart, chartModel);//from ww w . j a v a 2 s . c o m org.pentaho.chart.model.TwoAxisPlot twoAxisPlot = (org.pentaho.chart.model.TwoAxisPlot) chartModel .getPlot(); XYPlot xyPlot = chart.getXYPlot(); List<Integer> colors = getPlotColors(twoAxisPlot); for (int i = 0; i < colors.size(); i++) { for (int j = 0; j < xyPlot.getDatasetCount(); j++) { xyPlot.getRenderer(j).setSeriesPaint(i, new Color(0x00FFFFFF & colors.get(i))); } } Font domainAxisFont = ChartUtils.getFont(twoAxisPlot.getDomainAxis().getFontFamily(), twoAxisPlot.getDomainAxis().getFontStyle(), twoAxisPlot.getDomainAxis().getFontWeight(), twoAxisPlot.getDomainAxis().getFontSize()); Font rangeAxisFont = ChartUtils.getFont(twoAxisPlot.getRangeAxis().getFontFamily(), twoAxisPlot.getRangeAxis().getFontStyle(), twoAxisPlot.getRangeAxis().getFontWeight(), twoAxisPlot.getRangeAxis().getFontSize()); Font rangeTitleFont = ChartUtils.getFont(twoAxisPlot.getRangeAxis().getLegend().getFontFamily(), twoAxisPlot.getRangeAxis().getLegend().getFontStyle(), twoAxisPlot.getRangeAxis().getLegend().getFontWeight(), twoAxisPlot.getRangeAxis().getLegend().getFontSize()); Font domainTitleFont = ChartUtils.getFont(twoAxisPlot.getDomainAxis().getLegend().getFontFamily(), twoAxisPlot.getDomainAxis().getLegend().getFontStyle(), twoAxisPlot.getDomainAxis().getLegend().getFontWeight(), twoAxisPlot.getDomainAxis().getLegend().getFontSize()); NumberAxis domainAxis = (NumberAxis) xyPlot.getDomainAxis(); NumberAxis rangeAxis = (NumberAxis) xyPlot.getRangeAxis(); domainAxis.setAutoRangeIncludesZero(true); rangeAxis.setAutoRangeIncludesZero(true); AxesLabels axesLabels = getAxesLabels(chartModel); if ((axesLabels.rangeAxisLabel.length() > 0) && (rangeTitleFont != null)) { rangeAxis.setLabelFont(rangeTitleFont); } if ((axesLabels.domainAxisLabel.length() > 0) && (domainTitleFont != null)) { domainAxis.setLabelFont(domainTitleFont); } domainAxis.setVerticalTickLabels( twoAxisPlot.getHorizontalAxis().getLabelOrientation() == LabelOrientation.VERTICAL); if (domainAxisFont != null) { domainAxis.setTickLabelFont(domainAxisFont); } if (rangeAxisFont != null) { rangeAxis.setTickLabelFont(rangeAxisFont); } Number rangeMin = ((NumericAxis) twoAxisPlot.getRangeAxis()).getMinValue(); if (rangeMin != null) { rangeAxis.setLowerBound(rangeMin.doubleValue()); } Number rangeMax = ((NumericAxis) twoAxisPlot.getRangeAxis()).getMaxValue(); if (rangeMax != null) { rangeAxis.setUpperBound(rangeMax.doubleValue()); } }
From source file:com.stableapps.anglewraparounddemo.AngleWrapDemoMain.java
/** * Creates a sample chart./*from w w w . j a va 2 s . c o m*/ * * @return a sample chart. */ private JFreeChart createChart() { final XYDataset direction = createAngleDataset(600); final JFreeChart chart = ChartFactory.createTimeSeriesChart("Time", "Date", "Direction", direction, true, true, false); final XYPlot plot = chart.getXYPlot(); plot.getDomainAxis().setLowerMargin(0.0); plot.getDomainAxis().setUpperMargin(0.0); // configure the range axis to provide a fix set of TickUnits depending on size of chart NumberAxis rangeAxis = new NumberAxis() { /** * */ private static final long serialVersionUID = 1L; @Override public NumberTickUnit getTickUnit() { NumberTickUnit tickUnit = super.getTickUnit(); if (tickUnit.getSize() < 15) { return tickUnit; } else if (tickUnit.getSize() < 45) { return new NumberTickUnit(45); } else if (tickUnit.getSize() < 90) { return new NumberTickUnit(90); } else if (tickUnit.getSize() < 180) { return new NumberTickUnit(180); } else { return new NumberTickUnit(360); } } }; rangeAxis.setAutoRangeIncludesZero(false); plot.setRangeAxis(rangeAxis); final OverflowCondition overflowCondition = new OverflowCondition() { @Override public boolean isOverflow(double y0, double x0, double y1, double x1) { return Math.abs(y1 - y0) > 180; } }; XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false) { /** * */ private static final long serialVersionUID = 1L; double min = 0; double max = 360; LinearInterpolator interpolator = new LinearInterpolator(); @Override protected void drawPrimaryLine(XYItemRendererState state, Graphics2D g2, XYPlot plot, XYDataset dataset, int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) { if (item == 0) { return; } // get the data point... double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(y1) || Double.isNaN(x1)) { return; } double x0 = dataset.getXValue(series, item - 1); double y0 = dataset.getYValue(series, item - 1); if (Double.isNaN(y0) || Double.isNaN(x0)) { return; } if (overflowCondition.isOverflow(y0, x0, y1, x1)) { boolean overflowAtMax = y1 < y0; if (overflowAtMax) { LinearFunction lf = interpolator.interpolate(new double[] { y0, y1 + (max - min) }, new double[] { x0, x1 }); double xmid = lf.value(max); drawPrimaryLine(state, g2, plot, x0, y0, xmid, max, pass, series, item, domainAxis, rangeAxis, dataArea); drawPrimaryLine(state, g2, plot, xmid, min, x1, y1, pass, series, item, domainAxis, rangeAxis, dataArea); } else { LinearFunction lf = interpolator.interpolate(new double[] { y1 - (max - min), y0 }, new double[] { x1, x0 }); double xmid = lf.value(min); drawPrimaryLine(state, g2, plot, x0, y0, xmid, min, pass, series, item, domainAxis, rangeAxis, dataArea); drawPrimaryLine(state, g2, plot, xmid, max, x1, y1, pass, series, item, domainAxis, rangeAxis, dataArea); } } else { drawPrimaryLine(state, g2, plot, x0, y0, x1, y1, pass, series, item, domainAxis, rangeAxis, dataArea); } } private void drawPrimaryLine(XYItemRendererState state, Graphics2D g2, XYPlot plot, double x0, double y0, double x1, double y1, int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) { RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX0 = domainAxis.valueToJava2D(x0, dataArea, xAxisLocation); double transY0 = rangeAxis.valueToJava2D(y0, dataArea, yAxisLocation); double transX1 = domainAxis.valueToJava2D(x1, dataArea, xAxisLocation); double transY1 = rangeAxis.valueToJava2D(y1, dataArea, yAxisLocation); // only draw if we have good values if (Double.isNaN(transX0) || Double.isNaN(transY0) || Double.isNaN(transX1) || Double.isNaN(transY1)) { return; } PlotOrientation orientation = plot.getOrientation(); boolean visible; if (orientation == PlotOrientation.HORIZONTAL) { state.workingLine.setLine(transY0, transX0, transY1, transX1); } else if (orientation == PlotOrientation.VERTICAL) { state.workingLine.setLine(transX0, transY0, transX1, transY1); } visible = LineUtilities.clipLine(state.workingLine, dataArea); if (visible) { drawFirstPassShape(g2, pass, series, item, state.workingLine); } } @Override protected void drawPrimaryLineAsPath(XYItemRendererState state, Graphics2D g2, XYPlot plot, XYDataset dataset, int pass, int series, int item, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) { // get the data point... State s = (State) state; try { double x1 = dataset.getXValue(series, item); double y1 = dataset.getYValue(series, item); if (Double.isNaN(x1) && Double.isNaN(y1)) { s.setLastPointGood(false); return; } if (!s.isLastPointGood()) { ImmutablePair<Float, Float> xy = translate(plot, domainAxis, rangeAxis, dataArea, x1, y1); s.seriesPath.moveTo(xy.getLeft(), xy.getRight()); s.setLastPointGood(true); return; } double x0 = dataset.getXValue(series, item - 1); double y0 = dataset.getYValue(series, item - 1); if (overflowCondition.isOverflow(y0, x0, y1, x1)) { boolean overflowAtMax = y1 < y0; if (overflowAtMax) { LinearFunction lf = interpolator.interpolate(new double[] { y0, y1 + (max - min) }, new double[] { x0, x1 }); double xmid = lf.value(max); ImmutablePair<Float, Float> xy = translate(plot, domainAxis, rangeAxis, dataArea, xmid, max); s.seriesPath.lineTo(xy.getLeft(), xy.getRight()); xy = translate(plot, domainAxis, rangeAxis, dataArea, xmid, min); s.seriesPath.moveTo(xy.getLeft(), xy.getRight()); xy = translate(plot, domainAxis, rangeAxis, dataArea, x1, y1); s.seriesPath.lineTo(xy.getLeft(), xy.getRight()); } else { LinearFunction lf = interpolator.interpolate(new double[] { y1 - (max - min), y0 }, new double[] { x1, x0 }); double xmid = lf.value(min); ImmutablePair<Float, Float> xy = translate(plot, domainAxis, rangeAxis, dataArea, xmid, min); s.seriesPath.lineTo(xy.getLeft(), xy.getRight()); xy = translate(plot, domainAxis, rangeAxis, dataArea, xmid, max); s.seriesPath.moveTo(xy.getLeft(), xy.getRight()); xy = translate(plot, domainAxis, rangeAxis, dataArea, x1, y1); s.seriesPath.lineTo(xy.getLeft(), xy.getRight()); } } else { ImmutablePair<Float, Float> xy = translate(plot, domainAxis, rangeAxis, dataArea, x1, y1); s.seriesPath.lineTo(xy.getLeft(), xy.getRight()); } s.setLastPointGood(true); } finally { // if this is the last item, draw the path ... if (item == s.getLastItemIndex()) { // draw path drawFirstPassShape(g2, pass, series, item, s.seriesPath); } } } private ImmutablePair<Float, Float> translate(XYPlot plot, ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea, double x, double y) { RectangleEdge xAxisLocation = plot.getDomainAxisEdge(); RectangleEdge yAxisLocation = plot.getRangeAxisEdge(); double transX1 = domainAxis.valueToJava2D(x, dataArea, xAxisLocation); double transY1 = rangeAxis.valueToJava2D(y, dataArea, yAxisLocation); // update path to reflect latest point float xtrans = (float) transX1; float ytrans = (float) transY1; PlotOrientation orientation = plot.getOrientation(); if (orientation == PlotOrientation.HORIZONTAL) { xtrans = (float) transY1; ytrans = (float) transX1; } return new ImmutablePair<>(xtrans, ytrans); } }; renderer.setDrawSeriesLineAsPath(true); plot.setRenderer(0, renderer); return chart; }
From source file:no.met.jtimeseries.chart.ChartPlotter.java
/** * Add a line chart in the plot/*from w w w . java 2 s .c om*/ * * @param timeBase * The base time of the data: second, minute, hour, year or auto * @param phenomenon * Phenomenon to plot. * @param plotStyle * The style preference for the plot * */ public void addLineChart(TimeBase timeBase, NumberPhenomenon ph, PlotStyle plotStyle) { NumberPhenomenon phenomenon = ph.clone(); if (phenomenon.getItems().size() > 0) { XYItemRenderer renderer = RendererFactory.createRenderer(SplineStyle.STANDARD); // if using hybrid spline if (plotStyle.getSplineStyle().equalsIgnoreCase(SplineStyle.HYBRID)) { phenomenon.doHybridSpline(0.5d, 4); renderer = RendererFactory.createRenderer(SplineStyle.NONE); } if (plotStyle.getNonNegative()) { phenomenon.removeNegativeValues(); } XYDataset dataset = phenomenon.getTimeSeries(plotStyle.getTitle(), timeBase); renderer.setSeriesPaint(0, plotStyle.getSeriesColor()); renderer.setSeriesStroke(0, plotStyle.getStroke()); // hidden the legend by default renderer.setSeriesVisibleInLegend(0, false); plot.setDataset(plotIndex, dataset); plot.setRenderer(plotIndex, renderer); // render the range axis NumberAxis numberAxis; // null check for number axis if (plotStyle.getNumberAxis() == null) { numberAxis = new NumberAxis(plotStyle.getTitle()); numberAxis.setAutoRangeIncludesZero(false); numberAxis.setLabelPaint(plotStyle.getLabelColor()); numberAxis.setTickLabelPaint(plotStyle.getLabelColor()); // ugly calculation double max = phenomenon.getMaxValue(); double min = phenomenon.getMinValue(); // increase and decrease max, min respectiivly to get the // difference pf atleast 50 while ((max - min) <= plotStyle.getDifference()) { max++; min--; } int tUnit = (int) ((max - min) / plotStyle.getTotalTicks()); if (tUnit <= 1) { tUnit = 2; } int[] range = calculateAxisMaxMin(phenomenon, tUnit, plotStyle.getTotalTicks()); NumberTickUnit ntu = new NumberTickUnit(tUnit); numberAxis.setTickUnit(ntu); numberAxis.setRangeWithMargins(range[1], range[0]); } else { numberAxis = plotStyle.getNumberAxis(); } plot.setRangeAxis(rangeAxisIndex, numberAxis); Date minDate = phenomenon.getStartTime(); Date maxDate = phenomenon.getEndTime(); DateAxis domainAxis = (DateAxis) plot.getDomainAxis(); domainAxis.setRange(minDate, maxDate); plot.mapDatasetToRangeAxis(plotIndex, rangeAxisIndex); plotIndex++; rangeAxisIndex++; } }