List of usage examples for org.jfree.chart.axis NumberAxis setTickLabelFont
public void setTickLabelFont(Font font)
From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.ChartAxisFactory.java
public static ValueAxis createRangeAxis(RangeAxisConfig rangeAxisConfig, PlotInstance plotInstance) throws ChartPlottimeException { if (rangeAxisConfig.getValueType() == ValueType.UNKNOWN || rangeAxisConfig.getValueType() == ValueType.INVALID) { return null; } else {//from w w w . ja v a 2s . c om RangeAxisData rangeAxisData = plotInstance.getPlotData().getRangeAxisData(rangeAxisConfig); double initialUpperBound = rangeAxisData.getUpperViewBound(); double initialLowerBound = rangeAxisData.getLowerViewBound(); double upperBound = initialUpperBound; double lowerBound = initialLowerBound; // fetch old zooming LinkAndBrushMaster linkAndBrushMaster = plotInstance.getMasterPlotConfiguration() .getLinkAndBrushMaster(); Range axisZoom = linkAndBrushMaster.getRangeAxisZoom(rangeAxisConfig, plotInstance.getCurrentPlotConfigurationClone()); List<ValueSource> valueSources = rangeAxisConfig.getValueSources(); if (rangeAxisConfig.hasAbsolutStackedPlot()) { for (ValueSource valueSource : valueSources) { VisualizationType seriesType = valueSource.getSeriesFormat().getSeriesType(); if (seriesType == VisualizationType.BARS || seriesType == VisualizationType.AREA) { if (valueSource.getSeriesFormat().getStackingMode() == StackingMode.ABSOLUTE) { Pair<Double, Double> minMax = calculateUpperAndLowerBounds(valueSource, plotInstance); if (upperBound < minMax.getSecond()) { upperBound = minMax.getSecond(); } if (lowerBound > minMax.getFirst()) { lowerBound = minMax.getFirst(); } } } } } double margin = upperBound - lowerBound; if (lowerBound == upperBound) { margin = lowerBound; } if (margin == 0) { margin = 0.1; } double normalPad = RangeAxisConfig.padFactor * margin; if (rangeAxisConfig.isLogarithmicAxis()) { if (!rangeAxisConfig.isUsingUserDefinedLowerViewBound()) { lowerBound -= RangeAxisConfig.logPadFactor * lowerBound; } if (!rangeAxisConfig.isUsingUserDefinedUpperViewBound()) { upperBound += RangeAxisConfig.logPadFactor * upperBound; } } else { // add margin if (!rangeAxisConfig.isUsingUserDefinedLowerViewBound()) { lowerBound -= normalPad; } if (!rangeAxisConfig.isUsingUserDefinedUpperViewBound()) { upperBound += normalPad; } } boolean includeZero = false; if (isIncludingZero(rangeAxisConfig, initialLowerBound) && !rangeAxisConfig.isUsingUserDefinedLowerViewBound()) { // if so set lower bound to zero lowerBound = 0.0; includeZero = true; } boolean upToOne = false; // if there are only relative plots set upper Bound to 1.0 if (rangeAxisConfig.mustHaveUpperBoundOne(initialUpperBound) && !rangeAxisConfig.isUsingUserDefinedUpperViewBound()) { upperBound = 1.0; upToOne = true; } if (includeZero && !upToOne) { upperBound *= 1.05; } String label = rangeAxisConfig.getLabel(); if (label == null) { label = I18N.getGUILabel("plotter.unnamed_value_label"); } ValueAxis rangeAxis; if (rangeAxisConfig.getValueType() == ValueType.NOMINAL && !valueSources.isEmpty()) { // get union of distinct values of all plotValueConfigs on range axis int maxValue = Integer.MIN_VALUE; for (ValueSource valueSource : rangeAxisData.getRangeAxisConfig().getValueSources()) { ValueSourceData valueSourceData = plotInstance.getPlotData().getValueSourceData(valueSource); double maxValueInSource = valueSourceData.getMaxValue(); if (maxValueInSource > maxValue) { maxValue = (int) maxValueInSource; } } Vector<String> yValueStrings = new Vector<String>(maxValue); yValueStrings.setSize(maxValue + 1); ValueSourceData valueSourceData = plotInstance.getPlotData() .getValueSourceData(valueSources.get(0)); for (int i = 0; i <= maxValue; ++i) { yValueStrings.set(i, valueSourceData.getStringForValue(SeriesUsageType.MAIN_SERIES, i)); } String[] yValueStringArray = new String[yValueStrings.size()]; int i = 0; for (String s : yValueStrings) { yValueStringArray[i] = s; ++i; } CustomSymbolAxis symbolRangeAxis = new CustomSymbolAxis(null, yValueStringArray); symbolRangeAxis.setVisible(true); symbolRangeAxis.setAutoRangeIncludesZero(false); symbolRangeAxis.saveUpperBound(upperBound, initialUpperBound); symbolRangeAxis.saveLowerBound(lowerBound, initialLowerBound); symbolRangeAxis.setLabel(label); Font axesFont = plotInstance.getCurrentPlotConfigurationClone().getAxesFont(); if (axesFont != null) { symbolRangeAxis.setLabelFont(axesFont); symbolRangeAxis.setTickLabelFont(axesFont); } // set range if axis has been zoomed before if (axisZoom != null) { symbolRangeAxis.setRange(axisZoom); } rangeAxis = symbolRangeAxis; } else if (rangeAxisConfig.getValueType() == ValueType.NUMERICAL) { NumberAxis numberRangeAxis; if (rangeAxisConfig.isLogarithmicAxis()) { if (rangeAxisData.getMinYValue() <= 0) { throw new ChartPlottimeException("log_axis_contains_zero", label); } numberRangeAxis = new CustomLogarithmicAxis(null); ((CustomLogarithmicAxis) numberRangeAxis).saveUpperBound(upperBound, initialUpperBound); ((CustomLogarithmicAxis) numberRangeAxis).saveLowerBound(lowerBound, initialLowerBound); } else { numberRangeAxis = new CustomNumberAxis(); ((CustomNumberAxis) numberRangeAxis).saveUpperBound(upperBound, initialUpperBound); ((CustomNumberAxis) numberRangeAxis).saveLowerBound(lowerBound, initialLowerBound); } numberRangeAxis.setAutoRangeIncludesZero(false); numberRangeAxis.setVisible(true); numberRangeAxis.setLabel(label); Font axesFont = plotInstance.getCurrentPlotConfigurationClone().getAxesFont(); if (axesFont != null) { numberRangeAxis.setLabelFont(axesFont); numberRangeAxis.setTickLabelFont(axesFont); } // set range if axis has been zoomed before if (axisZoom != null) { numberRangeAxis.setRange(axisZoom); } rangeAxis = numberRangeAxis; } else if (rangeAxisConfig.getValueType() == ValueType.DATE_TIME) { CustomDateAxis dateRangeAxis; if (rangeAxisConfig.isLogarithmicAxis()) { throw new ChartPlottimeException("logarithmic_not_supported_for_value_type", label, ValueType.DATE_TIME); } else { dateRangeAxis = new CustomDateAxis(); } dateRangeAxis.saveUpperBound(upperBound, initialUpperBound); dateRangeAxis.saveLowerBound(lowerBound, initialLowerBound); dateRangeAxis.setVisible(true); dateRangeAxis.setLabel(label); Font axesFont = plotInstance.getCurrentPlotConfigurationClone().getAxesFont(); if (axesFont != null) { dateRangeAxis.setLabelFont(axesFont); } // set range if axis has been zoomed before if (axisZoom != null) { dateRangeAxis.setRange(axisZoom); } rangeAxis = dateRangeAxis; } else { throw new RuntimeException("Unknown value type. This should not happen"); } // configure format formatAxis(plotInstance.getCurrentPlotConfigurationClone(), rangeAxis); return rangeAxis; } }
From source file:com.rapidminer.gui.plotter.charts.MultipleSeriesChartPlotter.java
private JFreeChart createChart() { // create the chart... JFreeChart chart = ChartFactory.createXYLineChart(null, // chart title null, // x axis label null, // y axis label null, // data PlotOrientation.VERTICAL, false, // include legend true, // tooltips false // urls );/* w ww .ja v a 2 s . c o m*/ chart.setBackgroundPaint(Color.white); // get a reference to the plot for further customization... XYPlot plot = (XYPlot) chart.getPlot(); plot.setBackgroundPaint(Color.WHITE); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); plot.setDomainGridlinePaint(Color.LIGHT_GRAY); plot.setRangeGridlinePaint(Color.LIGHT_GRAY); // domain axis if ((indexAxis >= 0) && (!dataTable.isNominal(indexAxis))) { if ((dataTable.isDate(indexAxis)) || (dataTable.isDateTime(indexAxis))) { DateAxis domainAxis = new DateAxis(dataTable.getColumnName(indexAxis)); domainAxis.setTimeZone(Tools.getPreferredTimeZone()); chart.getXYPlot().setDomainAxis(domainAxis); } } else { plot.getDomainAxis().setStandardTickUnits(NumberAxis.createIntegerTickUnits(Locale.US)); ((NumberAxis) plot.getDomainAxis()).setAutoRangeStickyZero(false); ((NumberAxis) plot.getDomainAxis()).setAutoRangeIncludesZero(false); } ValueAxis xAxis = plot.getDomainAxis(); if (indexAxis > -1) { xAxis.setLabel(getDataTable().getColumnName(indexAxis)); } else { xAxis.setLabel(SERIESINDEX_LABEL); } xAxis.setAutoRange(true); xAxis.setLabelFont(LABEL_FONT_BOLD); xAxis.setTickLabelFont(LABEL_FONT); xAxis.setVerticalTickLabels(isLabelRotating()); if (indexAxis > 0) { if (getRangeForDimension(indexAxis) != null) { xAxis.setRange(getRangeForDimension(indexAxis)); } } else { if (getRangeForName(SERIESINDEX_LABEL) != null) { xAxis.setRange(getRangeForName(SERIESINDEX_LABEL)); } } // renderer and range axis synchronized (dataTable) { int numberOfSelectedColumns = 0; for (int c = 0; c < dataTable.getNumberOfColumns(); c++) { if (getPlotColumn(c)) { if (dataTable.isNumerical(c)) { numberOfSelectedColumns++; } } } int columnCount = 0; for (int c = 0; c < dataTable.getNumberOfColumns(); c++) { if (getPlotColumn(c)) { if (dataTable.isNumerical(c)) { // YIntervalSeries series = new // YIntervalSeries(this.dataTable.getColumnName(c)); XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries series = new XYSeries(dataTable.getColumnName(c)); Iterator<DataTableRow> i = dataTable.iterator(); int index = 1; while (i.hasNext()) { DataTableRow row = i.next(); double value = row.getValue(c); if ((indexAxis >= 0) && (!dataTable.isNominal(indexAxis))) { double indexValue = row.getValue(indexAxis); series.add(indexValue, value); } else { series.add(index++, value); } } dataset.addSeries(series); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); Color color = getColorProvider().getPointColor(1.0d); if (numberOfSelectedColumns > 1) { color = getColorProvider() .getPointColor(columnCount / (double) (numberOfSelectedColumns - 1)); } renderer.setSeriesPaint(0, color); renderer.setSeriesStroke(0, new BasicStroke(1.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); renderer.setSeriesShapesVisible(0, false); NumberAxis yAxis = new NumberAxis(dataTable.getColumnName(c)); if (getRangeForDimension(c) != null) { yAxis.setRange(getRangeForDimension(c)); } else { yAxis.setAutoRange(true); yAxis.setAutoRangeStickyZero(false); yAxis.setAutoRangeIncludesZero(false); } yAxis.setLabelFont(LABEL_FONT_BOLD); yAxis.setTickLabelFont(LABEL_FONT); if (numberOfSelectedColumns > 1) { yAxis.setAxisLinePaint(color); yAxis.setTickMarkPaint(color); yAxis.setLabelPaint(color); yAxis.setTickLabelPaint(color); } plot.setRangeAxis(columnCount, yAxis); plot.setRangeAxisLocation(columnCount, AxisLocation.TOP_OR_LEFT); plot.setDataset(columnCount, dataset); plot.setRenderer(columnCount, renderer); plot.mapDatasetToRangeAxis(columnCount, columnCount); columnCount++; } } } } chart.setBackgroundPaint(Color.white); return chart; }
From source file:unalcol.termites.boxplots.BestAgentsPercentageInfoCollected.java
/** * Creates a new demo.// w w w . j ava2 s . c o m * * @param title the frame title. * @param pf */ public BestAgentsPercentageInfoCollected(final String title, ArrayList<Double> pf) { super(title); String sDirectorio = experimentsDir; Hashtable<String, List> info = new Hashtable(); //String[] aMode = {"levywalk", "lwphevap", "hybrid", "hybrid3", "hybrid4"}; /*for (String mode : aMode) { info.put(mode, new ArrayList()); }*/ createSampleDataset(pf, info); AddDataFailingExperiments(sDirectorio, pf, info); final BoxAndWhiskerCategoryDataset dataset = addDataSet(info); final CategoryAxis xAxis = new CategoryAxis(""); //final NumberAxis yAxis = new NumberAxis("Information Collected"); final NumberAxis yAxis = new NumberAxis(""); yAxis.setAutoRangeIncludesZero(false); final BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer(); renderer.setFillBox(false); renderer.setToolTipGenerator(new BoxAndWhiskerToolTipGenerator()); final CategoryPlot plot = new CategoryPlot(dataset, xAxis, yAxis, renderer); Font font = new Font("Dialog", Font.PLAIN, 13); xAxis.setTickLabelFont(font); yAxis.setTickLabelFont(font); yAxis.setLabelFont(font); final JFreeChart chart = new JFreeChart("Information Collected " + getTitle(pf), new Font("SansSerif", Font.BOLD, 18), plot, true); final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(650, 370)); setContentPane(chartPanel); TextTitle legendText = null; if (pf.size() == 1) { legendText = new TextTitle("Population Size"); } else { legendText = new TextTitle("Population Size - Probability of Failure"); } legendText.setFont(font); legendText.setPosition(RectangleEdge.BOTTOM); chart.addSubtitle(legendText); chart.getLegend().setItemFont(font); FileOutputStream output; try { output = new FileOutputStream("BestAgentsPercentageInfoCollected" + pf + mazeMode + ".jpg"); ChartUtilities.writeChartAsJPEG(output, 1.0f, chart, 350, 350, null); } catch (FileNotFoundException ex) { Logger.getLogger(BestAgentsPercentageInfoCollected.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(BestAgentsPercentageInfoCollected.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:unalcol.termites.boxplots.BestAgentsRoundInfoCollected.java
/** * Creates a new demo./*from w w w.ja v a2s.c om*/ * * @param title the frame title. * @param pf */ public BestAgentsRoundInfoCollected(final String title, ArrayList<Double> pf) { super(title); String sDirectorio = experimentsDir; Hashtable<String, List> info = new Hashtable(); /*for (String mode : aMode) { info.put(mode, new ArrayList()); }*/ createSampleDataset(pf, info); AddDataFailingExperiments(sDirectorio, pf, info); final BoxAndWhiskerCategoryDataset dataset = addDataSet(info); System.out.println("info" + info); final CategoryAxis xAxis = new CategoryAxis(""); //final NumberAxis yAxis = new NumberAxis("Information Collected"); final NumberAxis yAxis = new NumberAxis(""); yAxis.setAutoRangeIncludesZero(false); final BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer(); renderer.setFillBox(false); renderer.setToolTipGenerator(new BoxAndWhiskerToolTipGenerator()); final CategoryPlot plot = new CategoryPlot(dataset, xAxis, yAxis, renderer); Font font = new Font("Dialog", Font.PLAIN, 13); xAxis.setTickLabelFont(font); yAxis.setTickLabelFont(font); yAxis.setLabelFont(font); final JFreeChart chart = new JFreeChart("Round of Best Agents " + getTitle(pf), new Font("SansSerif", Font.BOLD, 18), plot, true); final ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(650, 370)); setContentPane(chartPanel); TextTitle legendText = null; if (pf.size() == 1) { legendText = new TextTitle("Population Size"); } else { legendText = new TextTitle("Population Size - Probability of Failure"); } legendText.setFont(font); legendText.setPosition(RectangleEdge.BOTTOM); chart.addSubtitle(legendText); chart.getLegend().setItemFont(font); FileOutputStream output; try { output = new FileOutputStream("BestAgentsRound" + pf + mazeMode + ".jpg"); ChartUtilities.writeChartAsJPEG(output, 1.0f, chart, 450, 350, null); } catch (FileNotFoundException ex) { Logger.getLogger(BestAgentsRoundInfoCollected.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(BestAgentsRoundInfoCollected.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.StackedBarGroup.java
/** * Inherited by IChart.//from w ww . ja va 2 s. c o m * * @param chartTitle the chart title * @param dataset the dataset * * @return the j free chart */ public JFreeChart createChart(DatasetMap datasets) { logger.debug("IN"); CategoryDataset dataset = (CategoryDataset) datasets.getDatasets().get("1"); logger.debug("Get plot orientaton"); PlotOrientation plotOrientation = PlotOrientation.VERTICAL; if (horizontalView) { plotOrientation = PlotOrientation.HORIZONTAL; } JFreeChart chart = ChartFactory.createStackedBarChart(name, // chart title categoryLabel, // domain axis label valueLabel, // range axis label dataset, // data plotOrientation, // the plot orientation legend, // legend true, // tooltips false // urls ); chart.setBackgroundPaint(Color.white); CategoryPlot plot = (CategoryPlot) chart.getPlot(); plot.setBackgroundPaint(color); plot.setRangeGridlinePaint(Color.white); plot.setDomainGridlinePaint(Color.white); plot.setDomainGridlinesVisible(true); GroupedStackedBarRenderer renderer = new GroupedStackedBarRenderer(); KeyToGroupMap map = new KeyToGroupMap("G1"); int numElForGroup = 0; for (int idx = 0; idx < numGroups.intValue(); idx++) { for (int j = 0; j < numSerieForGroup.intValue(); j++) { try { String tmpSubCat = (String) subCategoryNames.get(j + idx * numSerieForGroup.intValue()); map.mapKeyToGroup(tmpSubCat, "G" + (idx + 1)); } catch (Exception e) { logger.error("out of range error in inserting in stacked bar group: continue anayway", e); } } } renderer.setSeriesToGroupMap(map); renderer.setItemMargin(0.0); renderer.setDrawBarOutline(false); renderer.setBaseItemLabelsVisible(true); if (percentageValue) renderer.setBaseItemLabelGenerator( new StandardCategoryItemLabelGenerator("{2}", new DecimalFormat("#,##.#%"))); else renderer.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator()); renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator()); if (maxBarWidth != null) { renderer.setMaximumBarWidth(maxBarWidth.doubleValue()); } boolean document_composition = false; if (mode.equalsIgnoreCase(SpagoBIConstants.DOCUMENT_COMPOSITION)) document_composition = true; /* MyCategoryUrlGenerator mycatUrl=new MyCategoryUrlGenerator(rootUrl); mycatUrl.setDocument_composition(document_composition); mycatUrl.setCategoryUrlLabel(categoryUrlName); mycatUrl.setSerieUrlLabel(serieUrlname); renderer.setItemURLGenerator(mycatUrl); */ TextTitle title = setStyleTitle(name, styleTitle); chart.setTitle(title); if (subName != null && !subName.equals("")) { TextTitle subTitle = setStyleTitle(subName, styleSubTitle); chart.addSubtitle(subTitle); } // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART... // set the background color for the chart... chart.setBackgroundPaint(color); NumberFormat nf = NumberFormat.getNumberInstance(locale); // set the range axis to display integers only... NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize())); rangeAxis.setLabelPaint(styleXaxesLabels.getColor()); rangeAxis .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize())); rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor()); rangeAxis.setNumberFormatOverride(nf); if (rangeIntegerValues == true) { rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); } if (rangeAxisLocation != null) { if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_LEFT")) { plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_LEFT); } else if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_RIGHT")) { plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_RIGHT); } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_RIGHT")) { plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_RIGHT); } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_LEFT")) { plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_LEFT); } } int seriesN = dataset.getRowCount(); int numSerieColored = 0; if (orderColorVector != null && orderColorVector.size() > 0) { logger.debug("color serie by SERIES_ORDER_COLORS template specification"); for (int i = 0; i < seriesN; i++) { if (orderColorVector.get(i) != null) { Color color = orderColorVector.get(i); renderer.setSeriesPaint(i, color); } } } else if (colorMap != null) { while (numSerieColored < seriesN) { for (int i = 1; i <= colorMap.size(); i++) { Color color = (Color) colorMap.get("SER" + i); Color gradient = new Color(Integer.decode("#FFFFFF").intValue()); if (gradientMap != null) gradient = (Color) gradientMap.get("SER" + i); if (color != null) { Paint p = new GradientPaint(0.0f, 0.0f, color, 0.0f, 0.0f, gradient); //renderer.setSeriesPaint(numSerieColored, color); renderer.setSeriesPaint(numSerieColored, p); } numSerieColored++; } } } renderer.setGradientPaintTransformer( new StandardGradientPaintTransformer(GradientPaintTransformType.HORIZONTAL)); MyStandardCategoryItemLabelGenerator generator = null; if (additionalLabels) { generator = new MyStandardCategoryItemLabelGenerator(catSerLabels, "{1}", NumberFormat.getInstance()); double orient = (-Math.PI / 2.0); if (styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) { orient = 0.0; } renderer.setBaseItemLabelFont( new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize())); renderer.setBaseItemLabelPaint(styleValueLabels.getColor()); renderer.setBaseItemLabelGenerator(generator); renderer.setBaseItemLabelsVisible(true); //vertical labels renderer.setBasePositiveItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient)); renderer.setBaseNegativeItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient)); //horizontal labels /* renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition( ItemLabelAnchor.CENTER, TextAnchor.CENTER)); renderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition( ItemLabelAnchor.CENTER, TextAnchor.CENTER)); */ } SubCategoryAxis domainAxis = new SubCategoryAxis(categoryLabel + " / " + subCategoryLabel); String subCatLabel = ""; for (int j = 1; j <= numGroups.intValue(); j++) { if (subCatLabelsMap != null) subCatLabel = (String) subCatLabelsMap.get("CAT" + j); else subCatLabel = subCategoryLabel; domainAxis.addSubCategory(subCatLabel); domainAxis .setLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize())); domainAxis.setLabelPaint(styleYaxesLabels.getColor()); domainAxis.setTickLabelFont( new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize())); domainAxis.setTickLabelPaint(styleYaxesLabels.getColor()); } plot.setDomainAxis(domainAxis); plot.setRenderer(renderer); /* domainAxis.setCategoryLabelPositions( CategoryLabelPositions.createUpRotationLabelPositions( Math.PI / 6.0)); */ if (legend == true) drawLegend(chart); logger.debug("OUT"); 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 w w.j a v a2 s . 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:org.glotaran.core.datadisplayers.multispec.MultiSpecEditorTopComponent.java
private void MakeImageChart(ColorCodedImageDataset dataset) { double range = Math.abs(data.getMaxInt() - data.getMinInt()); double dataMin, dataMax; if (range == 0.0) { dataMin = data.getMinInt() - 0.1; dataMax = data.getMaxInt() + 0.1; } else {/*from www . j av a 2 s . c o m*/ dataMin = data.getMinInt(); dataMax = data.getMaxInt(); } PaintScale ps = new RainbowPaintScale(dataMin, dataMax); this.chartMultiSpec = createChart(new XYSeriesCollection()); this.chartMultiSpec.setBackgroundPaint(JFreeChart.DEFAULT_BACKGROUND_PAINT); XYPlot tempPlot = (XYPlot) this.chartMultiSpec.getPlot(); this.wholeXRange = tempPlot.getDomainAxis().getRange(); this.wholeYRange = tempPlot.getRangeAxis().getRange(); //added axes labeles on the image // DecimalFormat formatter = new DecimalFormat("##0E0"); // NumberAxis xAxis = new NumberAxis("Wavelength "); // // // double[] x2values = data.getIntenceImY(); // double x2range = Math.abs(x2values[0] - x2values[x2values.length - 1]); // if (x2range<=0) { // for (int i = 0; i < x2values.length; i++) { // x2values[i]=i; // } // } // // int numberOfTicks = Math.min(data.getIntenceImY().length,MAX_NO_TICKS); // NonLinearNumberTickUnit xTickUnit = new NonLinearNumberTickUnit(x2values.length/numberOfTicks, formatter,x2values); // xAxis.setTickUnit(xTickUnit); // xAxis.setTickLabelsVisible(true); // tempPlot.setDomainAxis(xAxis); // // NumberAxis yAxis = new NumberAxis("? Wavelength"); // // formatter = new DecimalFormat("##0.#E0"); // numberOfTicks = Math.min(data.getX3().length,MAX_NO_TICKS); // NonLinearNumberTickUnit yTickUnit = new NonLinearNumberTickUnit(data.getX3().length/numberOfTicks, formatter,data.getX3(),false); // yAxis.setTickUnit(yTickUnit); // yAxis.setTickLabelsVisible(true); // tempPlot.setRangeAxis(yAxis); chartPanelMultiSpec = new HeightMapPanel(chartMultiSpec, true); chartPanelMultiSpec.setFillZoomRectangle(true); chartPanelMultiSpec.setMouseWheelEnabled(true); chartPanelMultiSpec.setZoomFillPaint(new Color(68, 68, 78, 63)); jpMultiSpecImage.removeAll(); // chpanImage.setSize(jPSpecImage.getMaximumSize()); jpMultiSpecImage.setLayout(new BorderLayout()); ImageCrosshairLabelGenerator crossLabGenVerticalCut = new ImageCrosshairLabelGenerator(data.getIntenceImY(), false); ImageCrosshairLabelGenerator crossLabGenHorisontalCut = new ImageCrosshairLabelGenerator( data.getIntenceImX(), false); ImageCrosshairLabelGenerator crossLabGenTimeSlise = new ImageCrosshairLabelGenerator(data.getX(), false); crhVerticalCut = createCroshair(Color.red, crossLabGenVerticalCut); crhHorisontalCut = createCroshair(Color.gray, crossLabGenHorisontalCut); crhTimeSlice = createCroshair(Color.red, null); CrosshairOverlay overlay = new CrosshairOverlay(); overlay.addDomainCrosshair(crhVerticalCut); overlay.addRangeCrosshair(crhHorisontalCut); chartPanelMultiSpec.addOverlay(overlay); jpMultiSpecImage.add(chartPanelMultiSpec); //TODO: auto scale the JSlider jSColum to the size of the chart //chpanImage.getChartRenderingInfo().getChartArea().getWidth(); //jSColum.setBounds(jSColum.getBounds().x, jSColum.getBounds().y,(int)chpanImage.getChartRenderingInfo().getChartArea().getBounds().width,jSColum.getHeight()); chartMultiSpec.addChangeListener((ChartChangeListener) this); subchartVerticalCutTrace = createXYPlot(PlotOrientation.HORIZONTAL, AxisLocation.BOTTOM_OR_RIGHT, data.getIntenceImX(), jpVerticalCut, false, null); subchartHorisontalTrace = createXYPlot(PlotOrientation.VERTICAL, AxisLocation.BOTTOM_OR_RIGHT, data.getIntenceImY(), jpHorisontalCut, false, null); CrosshairOverlay overlayTime = new CrosshairOverlay(); overlayTime.addDomainCrosshair(crhTimeSlice); subchartTimeTrace = createXYPlot(PlotOrientation.VERTICAL, AxisLocation.BOTTOM_OR_LEFT, data.getX(), jpTimeeTrace, false, overlayTime); NumberAxis scaleAxis = new NumberAxis(); scaleAxis.setAxisLinePaint(Color.black); scaleAxis.setTickMarkPaint(Color.black); scaleAxis.setRange(data.getMinInt(), data.getMaxInt()); scaleAxis.setTickLabelFont(new Font("Dialog", Font.PLAIN, 12)); PaintScaleLegend legend = new PaintScaleLegend(ps, scaleAxis); legend.setAxisLocation(AxisLocation.BOTTOM_OR_RIGHT); legend.setMargin(new RectangleInsets(5, 5, 5, 5)); legend.setStripWidth(15); legend.setPosition(RectangleEdge.RIGHT); legend.setBackgroundPaint(chartMultiSpec.getBackgroundPaint()); chartMultiSpec.addSubtitle(legend); this.chartMultiSpec.addChangeListener((ChartChangeListener) this); jSVerticalCut.setValueIsAdjusting(true); jSVerticalCut.setMaximum(dataset.GetImageWidth() - 1); jSVerticalCut.setMinimum(0); // jSVerticalCut.setValue(0); jSVerticalCut.setValueIsAdjusting(false); jsHorisontalCut.setValueIsAdjusting(true); jsHorisontalCut.setMaximum(dataset.GetImageHeigth() - 1); jsHorisontalCut.setMinimum(0); jsHorisontalCut.setValueIsAdjusting(false); jsTimeSlice.setValueIsAdjusting(true); jsTimeSlice.setMaximum(data.getNt() - 1); jsTimeSlice.setMinimum(0); jsTimeSlice.setValueIsAdjusting(false); }
From source file:asl.util.PlotMaker2.java
public void writePlot(String fileName) { //System.out.format("== plotTitle=[%s] fileName=[%s]\n", plotTitle, fileName); File outputFile = new File(fileName); // Check that we will be able to output the file without problems and if not --> return if (!checkFileOut(outputFile)) { System.out.format("== plotMaker: request to output plot=[%s] but we are unable to create it " + " --> skip plot\n", fileName); return;//from ww w . j av a2 s. com } NumberAxis horizontalAxis = new NumberAxis("x-axis default"); // x = domain if (fileName.contains("nlnm") || fileName.contains("coher") || fileName.contains("stn")) { // NLNM or StationDeviation horizontalAxis = new LogarithmicAxis("Period (sec)"); horizontalAxis.setRange(new Range(1, 11000)); horizontalAxis.setTickUnit(new NumberTickUnit(5.0)); } else { // EventCompareSynthetics/StrongMotion horizontalAxis = new NumberAxis("Time (s)"); double x[] = panels.get(0).getTraces().get(0).getxData(); horizontalAxis.setRange(new Range(x[0], x[x.length - 1])); } CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis); combinedPlot.setGap(15.); // Loop over (3) panels for this plot: for (Panel panel : panels) { NumberAxis verticalAxis = new NumberAxis("y-axis default"); // y = range if (fileName.contains("nlnm") || fileName.contains("stn")) { // NLNM or StationDeviation verticalAxis = new NumberAxis("PSD 10log10(m**2/s**4)/Hz dB"); verticalAxis.setRange(new Range(-190, -95)); verticalAxis.setTickUnit(new NumberTickUnit(5.0)); } else if (fileName.contains("coher")) { // Coherence verticalAxis = new NumberAxis("Coherence, Gamma"); verticalAxis.setRange(new Range(0, 1.2)); verticalAxis.setTickUnit(new NumberTickUnit(0.1)); } else { // EventCompareSynthetics/StrongMotion verticalAxis = new NumberAxis("Displacement (m)"); } Font fontPlain = new Font("Verdana", Font.PLAIN, 14); Font fontBold = new Font("Verdana", Font.BOLD, 18); verticalAxis.setLabelFont(fontBold); verticalAxis.setTickLabelFont(fontPlain); horizontalAxis.setLabelFont(fontBold); horizontalAxis.setTickLabelFont(fontPlain); XYSeriesCollection seriesCollection = new XYSeriesCollection(); XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(); XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, horizontalAxis, verticalAxis, renderer); xyplot.setDomainGridlinesVisible(true); xyplot.setRangeGridlinesVisible(true); xyplot.setRangeGridlinePaint(Color.black); xyplot.setDomainGridlinePaint(Color.black); // Plot each trace on this panel: int iTrace = 0; for (Trace trace : panel.getTraces()) { XYSeries series = new XYSeries(trace.getName()); double xdata[] = trace.getxData(); double ydata[] = trace.getyData(); for (int k = 0; k < xdata.length; k++) { series.add(xdata[k], ydata[k]); } renderer.setSeriesPaint(iTrace, trace.getColor()); renderer.setSeriesStroke(iTrace, trace.getStroke()); renderer.setSeriesLinesVisible(iTrace, true); renderer.setSeriesShapesVisible(iTrace, false); seriesCollection.addSeries(series); iTrace++; } // Add Annotations for each trace - This is done in a separate loop so that // the upper/lower limits for this panel will be known double xmin = horizontalAxis.getRange().getLowerBound(); double xmax = horizontalAxis.getRange().getUpperBound(); double ymin = verticalAxis.getRange().getLowerBound(); double ymax = verticalAxis.getRange().getUpperBound(); double delX = Math.abs(xmax - xmin); double delY = Math.abs(ymax - ymin); // Annotation (x,y) in normalized units - where upper-right corner = (1,1) double xAnn = 0.97; // Right center coords of the trace name (e.g., "00-LHZ") double yAnn = 0.95; double yOff = 0.05; // Vertical distance between different trace legends iTrace = 0; for (Trace trace : panel.getTraces()) { if (!trace.getName().contains("NLNM") && !trace.getName().contains("NHNM")) { // x1 > x2 > x3, e.g.: // o-------o 00-LHZ // x3 x2 x1 double scale = .01; // Controls distance between trace label and line segment double xL = .04; // Length of trace line segment in legend double xAnn2 = xAnn - scale * trace.getName().length(); double xAnn3 = xAnn - scale * trace.getName().length() - xL; double x1 = xAnn * delX + xmin; // Right hand x-coord of text in range units double x2 = xAnn2 * delX + xmin; // x-coord of line segment end in range units double x3 = xAnn3 * delX + xmin; // x-coord of line segment end in range units double y = (yAnn - (iTrace * yOff)) * delY + ymin; if (horizontalAxis instanceof LogarithmicAxis) { double logMin = Math.log10(xmin); double logMax = Math.log10(xmax); delX = logMax - logMin; x1 = Math.pow(10, xAnn * delX + logMin); x2 = Math.pow(10, xAnn2 * delX + logMin); x3 = Math.pow(10, xAnn3 * delX + logMin); } xyplot.addAnnotation(new XYLineAnnotation(x3, y, x2, y, trace.getStroke(), trace.getColor())); XYTextAnnotation xyText = new XYTextAnnotation(trace.getName(), x1, y); xyText.setFont(new Font("Verdana", Font.BOLD, 18)); xyText.setTextAnchor(TextAnchor.CENTER_RIGHT); xyplot.addAnnotation(xyText); } iTrace++; } combinedPlot.add(xyplot, 1); } // panel final JFreeChart chart = new JFreeChart(combinedPlot); chart.setTitle(new TextTitle(plotTitle, new Font("Verdana", Font.BOLD, 18))); chart.removeLegend(); try { ChartUtilities.saveChartAsPNG(outputFile, chart, 1400, 1400); } catch (IOException e) { System.err.println("Problem occurred creating chart."); } }
From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.CombinedCategoryBar.java
public JFreeChart createChart(DatasetMap datasets) { logger.debug("IN"); // recover the datasets DefaultCategoryDataset datasetBarFirstAxis = (DefaultCategoryDataset) datasets.getDatasets().get("1-bar"); DefaultCategoryDataset datasetBarSecondAxis = (DefaultCategoryDataset) datasets.getDatasets().get("2-bar"); DefaultCategoryDataset datasetLineFirstAxis = (DefaultCategoryDataset) datasets.getDatasets().get("1-line"); DefaultCategoryDataset datasetLineSecondAxis = (DefaultCategoryDataset) datasets.getDatasets() .get("2-line"); // create the two subplots CategoryPlot subPlot1 = new CategoryPlot(); CategoryPlot subPlot2 = new CategoryPlot(); CombinedDomainCategoryPlot plot = new CombinedDomainCategoryPlot(); subPlot1.setDataset(0, datasetBarFirstAxis); subPlot2.setDataset(0, datasetBarSecondAxis); subPlot1.setDataset(1, datasetLineFirstAxis); subPlot2.setDataset(1, datasetLineSecondAxis); // localize numbers on y axis NumberFormat nf = (NumberFormat) NumberFormat.getNumberInstance(locale); // Range Axis 1 NumberAxis rangeAxis = new NumberAxis(getValueLabel()); rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize())); rangeAxis.setLabelPaint(styleXaxesLabels.getColor()); rangeAxis .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize())); rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor()); rangeAxis.setUpperMargin(0.10);/* ww w .j a va 2 s. c om*/ rangeAxis.setNumberFormatOverride(nf); subPlot1.setRangeAxis(rangeAxis); if (rangeIntegerValues == true) { rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); } // Range Axis 2 NumberAxis rangeAxis2 = new NumberAxis(secondAxisLabel); rangeAxis2.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize())); rangeAxis2.setLabelPaint(styleXaxesLabels.getColor()); rangeAxis2 .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize())); rangeAxis2.setTickLabelPaint(styleXaxesLabels.getColor()); rangeAxis2.setUpperMargin(0.10); rangeAxis2.setNumberFormatOverride(nf); subPlot2.setRangeAxis(rangeAxis2); if (rangeIntegerValues == true) { rangeAxis2.setStandardTickUnits(NumberAxis.createIntegerTickUnits()); } // Category Axis CategoryAxis domainAxis = new CategoryAxis(getCategoryLabel()); domainAxis.setLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize())); domainAxis.setLabelPaint(styleYaxesLabels.getColor()); domainAxis .setTickLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize())); domainAxis.setTickLabelPaint(styleYaxesLabels.getColor()); domainAxis.setUpperMargin(0.10); plot.setDomainAxis(domainAxis); plot.setOrientation(PlotOrientation.VERTICAL); plot.setRangeGridlinesVisible(true); plot.setDomainGridlinesVisible(true); // Add subplots to main plot plot.add(subPlot1, 1); plot.add(subPlot2, 2); MyStandardCategoryItemLabelGenerator generator = null; // value labels and additional values are mutually exclusive if (showValueLabels == true) additionalLabels = false; if (additionalLabels) { generator = new MyStandardCategoryItemLabelGenerator(catSerLabels, "{1}", NumberFormat.getInstance()); } // Create Renderers! CategoryItemRenderer barRenderer1 = new BarRenderer(); CategoryItemRenderer barRenderer2 = new BarRenderer(); LineAndShapeRenderer lineRenderer1 = (useLinesRenderers == true) ? new LineAndShapeRenderer() : null; LineAndShapeRenderer lineRenderer2 = (useLinesRenderers == true) ? new LineAndShapeRenderer() : null; subPlot1.setRenderer(0, barRenderer1); subPlot2.setRenderer(0, barRenderer2); if (useLinesRenderers == true) { subPlot1.setRenderer(1, lineRenderer1); subPlot2.setRenderer(1, lineRenderer2); // no shapes for line_no_shapes series for (Iterator iterator = lineNoShapeSeries1.iterator(); iterator.hasNext();) { String ser = (String) iterator.next(); // if there iS a abel associated search for that String label = null; if (seriesLabelsMap != null) { label = (String) seriesLabelsMap.get(ser); } if (label == null) label = ser; int index = datasetLineFirstAxis.getRowIndex(label); if (index != -1) { lineRenderer1.setSeriesShapesVisible(index, false); } } for (Iterator iterator = lineNoShapeSeries2.iterator(); iterator.hasNext();) { String ser = (String) iterator.next(); // if there iS a abel associated search for that String label = null; if (seriesLabelsMap != null) { label = (String) seriesLabelsMap.get(ser); } if (label == null) label = ser; int index = datasetLineSecondAxis.getRowIndex(label); if (index != -1) { lineRenderer2.setSeriesShapesVisible(index, false); } } } // add tooltip if enabled if (enableToolTips) { MyCategoryToolTipGenerator generatorToolTip = new MyCategoryToolTipGenerator(freeToolTips, seriesTooltip, categoriesTooltip, seriesCaptions); barRenderer1.setToolTipGenerator(generatorToolTip); barRenderer2.setToolTipGenerator(generatorToolTip); if (useLinesRenderers) { lineRenderer1.setToolTipGenerator(generatorToolTip); lineRenderer2.setToolTipGenerator(generatorToolTip); } } subPlot1.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); subPlot2.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); // COnfigure renderers: I do in extensive way so will be easier to add customization in the future if (maxBarWidth != null) { ((BarRenderer) barRenderer1).setMaximumBarWidth(maxBarWidth.doubleValue()); ((BarRenderer) barRenderer2).setMaximumBarWidth(maxBarWidth.doubleValue()); } // Values or addition Labels for first BAR Renderer if (showValueLabels) { barRenderer1.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator()); barRenderer1.setBaseItemLabelsVisible(true); barRenderer1.setBaseItemLabelFont( new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize())); barRenderer1.setBaseItemLabelPaint(styleValueLabels.getColor()); barRenderer1.setBasePositiveItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT)); barRenderer1.setBaseNegativeItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT)); barRenderer2.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator()); barRenderer2.setBaseItemLabelsVisible(true); barRenderer2.setBaseItemLabelFont( new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize())); barRenderer2.setBaseItemLabelPaint(styleValueLabels.getColor()); barRenderer2.setBasePositiveItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT)); barRenderer2.setBaseNegativeItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT)); } else if (additionalLabels) { barRenderer1.setBaseItemLabelGenerator(generator); barRenderer2.setBaseItemLabelGenerator(generator); double orient = (-Math.PI / 2.0); if (styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) { orient = 0.0; } barRenderer1.setBasePositiveItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient)); barRenderer1.setBaseNegativeItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient)); barRenderer2.setBasePositiveItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient)); barRenderer2.setBaseNegativeItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient)); } // Values or addition Labels for line Renderers if requested if (useLinesRenderers == true) { if (showValueLabels) { lineRenderer1.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator()); lineRenderer1.setBaseItemLabelsVisible(true); lineRenderer1.setBaseItemLabelFont( new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize())); lineRenderer1.setBaseItemLabelPaint(styleValueLabels.getColor()); lineRenderer1.setBasePositiveItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT)); lineRenderer1.setBaseNegativeItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT)); lineRenderer2.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator()); lineRenderer2.setBaseItemLabelsVisible(true); lineRenderer2.setBaseItemLabelFont( new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize())); lineRenderer2.setBaseItemLabelPaint(styleValueLabels.getColor()); lineRenderer2.setBasePositiveItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT)); lineRenderer2.setBaseNegativeItemLabelPosition( new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT)); } else if (additionalLabels) { lineRenderer1.setBaseItemLabelGenerator(generator); lineRenderer2.setBaseItemLabelGenerator(generator); double orient = (-Math.PI / 2.0); if (styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) { orient = 0.0; } lineRenderer1.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient)); lineRenderer1.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient)); lineRenderer2.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient)); lineRenderer2.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, orient)); } } // Bar Dataset Colors! if (colorMap != null) { int idx = -1; for (Iterator iterator = datasetBarFirstAxis.getRowKeys().iterator(); iterator.hasNext();) { idx++; String serName = (String) iterator.next(); String labelName = ""; int index = -1; if (seriesCaptions != null && seriesCaptions.size() > 0) { labelName = serName; serName = (String) seriesCaptions.get(serName); index = datasetBarFirstAxis.getRowIndex(labelName); } else index = datasetBarFirstAxis.getRowIndex(serName); Color color = (Color) colorMap.get(serName); if (color != null) { barRenderer1.setSeriesPaint(index, color); } } for (Iterator iterator = datasetBarSecondAxis.getRowKeys().iterator(); iterator.hasNext();) { idx++; String serName = (String) iterator.next(); String labelName = ""; int index = -1; if (seriesCaptions != null && seriesCaptions.size() > 0) { labelName = serName; serName = (String) seriesCaptions.get(serName); index = datasetBarSecondAxis.getRowIndex(labelName); } else index = datasetBarSecondAxis.getRowIndex(serName); Color color = (Color) colorMap.get(serName); if (color != null) { barRenderer2.setSeriesPaint(index, color); } } } // LINE Dataset Colors! if (useLinesRenderers == true) { if (colorMap != null) { int idx = -1; for (Iterator iterator = datasetLineFirstAxis.getRowKeys().iterator(); iterator.hasNext();) { idx++; String serName = (String) iterator.next(); String labelName = ""; int index = -1; if (seriesCaptions != null && seriesCaptions.size() > 0) { labelName = serName; serName = (String) seriesCaptions.get(serName); index = datasetLineFirstAxis.getRowIndex(labelName); } else index = datasetLineFirstAxis.getRowIndex(serName); Color color = (Color) colorMap.get(serName); if (color != null) { lineRenderer1.setSeriesPaint(index, color); } } for (Iterator iterator = datasetLineSecondAxis.getRowKeys().iterator(); iterator.hasNext();) { idx++; String serName = (String) iterator.next(); String labelName = ""; int index = -1; if (seriesCaptions != null && seriesCaptions.size() > 0) { labelName = serName; serName = (String) seriesCaptions.get(serName); index = datasetLineSecondAxis.getRowIndex(labelName); } else index = datasetLineSecondAxis.getRowIndex(serName); Color color = (Color) colorMap.get(serName); if (color != null) { lineRenderer2.setSeriesPaint(index, color); } } } } //defines url for drill boolean document_composition = false; if (mode.equalsIgnoreCase(SpagoBIConstants.DOCUMENT_COMPOSITION)) document_composition = true; logger.debug("Calling Url Generation"); MyCategoryUrlGenerator mycatUrl = null; if (super.rootUrl != null) { logger.debug("Set MycatUrl"); mycatUrl = new MyCategoryUrlGenerator(super.rootUrl); mycatUrl.setDocument_composition(document_composition); mycatUrl.setCategoryUrlLabel(super.categoryUrlName); mycatUrl.setSerieUrlLabel(super.serieUrlname); mycatUrl.setDrillDocTitle(drillDocTitle); mycatUrl.setTarget(target); } if (mycatUrl != null) { barRenderer1.setItemURLGenerator(mycatUrl); barRenderer2.setItemURLGenerator(mycatUrl); if (useLinesRenderers) { lineRenderer1.setItemURLGenerator(mycatUrl); lineRenderer2.setItemURLGenerator(mycatUrl); } } plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45); JFreeChart chart = new JFreeChart(plot); TextTitle title = setStyleTitle(name, styleTitle); chart.setTitle(title); if (subName != null && !subName.equals("")) { TextTitle subTitle = setStyleTitle(subName, styleSubTitle); chart.addSubtitle(subTitle); } chart.setBackgroundPaint(Color.white); // I want to re order the legend LegendItemCollection legends = plot.getLegendItems(); // legend Temp HashMap<String, LegendItem> legendTemp = new HashMap<String, LegendItem>(); Vector<String> alreadyInserted = new Vector<String>(); for (int i = 0; i < legends.getItemCount(); i++) { LegendItem item = legends.get(i); String label = item.getLabel(); legendTemp.put(label, item); } LegendItemCollection newLegend = new LegendItemCollection(); // force the order of the ones specified for (Iterator iterator = seriesOrder.iterator(); iterator.hasNext();) { String serie = (String) iterator.next(); if (legendTemp.keySet().contains(serie)) { newLegend.add(legendTemp.get(serie)); alreadyInserted.add(serie); } } // check that there are no serie not specified, otherwise add them for (Iterator iterator = legendTemp.keySet().iterator(); iterator.hasNext();) { String serie = (String) iterator.next(); if (!alreadyInserted.contains(serie)) { newLegend.add(legendTemp.get(serie)); } } plot.setFixedLegendItems(newLegend); if (legend == true) drawLegend(chart); logger.debug("OUT"); return chart; }
From source file:asl.plotmaker.PlotMaker2.java
public void writePlot(String fileName) { // System.out.format("== plotTitle=[%s] fileName=[%s]\n", plotTitle, // fileName); File outputFile = new File(fileName); // Check that we will be able to output the file without problems and if // not --> return if (!checkFileOut(outputFile)) { // System.out.format("== plotMaker: request to output plot=[%s] but we are unable to create it " // + " --> skip plot\n", fileName ); logger.warn("== Request to output plot=[{}] but we are unable to create it " + " --> skip plot\n", fileName);//from ww w.ja v a2 s . c o m return; } NumberAxis horizontalAxis = new NumberAxis("x-axis default"); // x = // domain if (fileName.contains("alnm") || fileName.contains("nlnm") || fileName.contains("coher") || fileName.contains("stn")) { // NLNM or StationDeviation horizontalAxis = new LogarithmicAxis("Period (sec)"); horizontalAxis.setRange(new Range(1, 11000)); horizontalAxis.setTickUnit(new NumberTickUnit(5.0)); } else { // EventCompareSynthetics/StrongMotion horizontalAxis = new NumberAxis("Time (s)"); double x[] = panels.get(0).getTraces().get(0).getxData(); horizontalAxis.setRange(new Range(x[0], x[x.length - 1])); } CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis); combinedPlot.setGap(15.); // Loop over (3) panels for this plot: for (Panel panel : panels) { NumberAxis verticalAxis = new NumberAxis("y-axis default"); // y = // range if (fileName.contains("alnm") || fileName.contains("nlnm") || fileName.contains("stn")) { // NLNM // or // StationDeviation verticalAxis = new NumberAxis("PSD 10log10(m**2/s**4)/Hz dB"); verticalAxis.setRange(new Range(-190, -80)); verticalAxis.setTickUnit(new NumberTickUnit(5.0)); } else if (fileName.contains("coher")) { // Coherence verticalAxis = new NumberAxis("Coherence, Gamma"); verticalAxis.setRange(new Range(0, 1.2)); verticalAxis.setTickUnit(new NumberTickUnit(0.1)); } else { // EventCompareSynthetics/StrongMotion verticalAxis = new NumberAxis("Displacement (m)"); } Font fontPlain = new Font("Verdana", Font.PLAIN, 14); Font fontBold = new Font("Verdana", Font.BOLD, 18); verticalAxis.setLabelFont(fontBold); verticalAxis.setTickLabelFont(fontPlain); horizontalAxis.setLabelFont(fontBold); horizontalAxis.setTickLabelFont(fontPlain); XYSeriesCollection seriesCollection = new XYSeriesCollection(); XYDotRenderer renderer = new XYDotRenderer(); XYPlot xyplot = new XYPlot(seriesCollection, horizontalAxis, verticalAxis, renderer); xyplot.setDomainGridlinesVisible(true); xyplot.setRangeGridlinesVisible(true); xyplot.setRangeGridlinePaint(Color.black); xyplot.setDomainGridlinePaint(Color.black); // Plot each trace on this panel: int iTrace = 0; for (Trace trace : panel.getTraces()) { XYSeries series = new XYSeries(trace.getName()); double xdata[] = trace.getxData(); double ydata[] = trace.getyData(); for (int k = 0; k < xdata.length; k++) { series.add(xdata[k], ydata[k]); } renderer.setSeriesPaint(iTrace, trace.getColor()); renderer.setSeriesStroke(iTrace, trace.getStroke()); seriesCollection.addSeries(series); iTrace++; } // Add Annotations for each trace - This is done in a separate loop // so that // the upper/lower limits for this panel will be known double xmin = horizontalAxis.getRange().getLowerBound(); double xmax = horizontalAxis.getRange().getUpperBound(); double ymin = verticalAxis.getRange().getLowerBound(); double ymax = verticalAxis.getRange().getUpperBound(); double delX = Math.abs(xmax - xmin); double delY = Math.abs(ymax - ymin); // Annotation (x,y) in normalized units - where upper-right corner = // (1,1) double xAnn = 0.97; // Right center coords of the trace name (e.g., // "00-LHZ") double yAnn = 0.95; double yOff = 0.05; // Vertical distance between different trace // legends iTrace = 0; for (Trace trace : panel.getTraces()) { if (!trace.getName().contains("NLNM") && !trace.getName().contains("NHNM") && !trace.getName().contains("ALNM")) { // x1 > x2 > x3, e.g.: // o-------o 00-LHZ // x3 x2 x1 double scale = .01; // Controls distance between trace label // and line segment double xL = .04; // Length of trace line segment in legend double xAnn2 = xAnn - scale * trace.getName().length(); double xAnn3 = xAnn - scale * trace.getName().length() - xL; double x1 = xAnn * delX + xmin; // Right hand x-coord of // text in range units double x2 = xAnn2 * delX + xmin; // x-coord of line segment // end in range units double x3 = xAnn3 * delX + xmin; // x-coord of line segment // end in range units double y = (yAnn - (iTrace * yOff)) * delY + ymin; if (horizontalAxis instanceof LogarithmicAxis) { double logMin = Math.log10(xmin); double logMax = Math.log10(xmax); delX = logMax - logMin; x1 = Math.pow(10, xAnn * delX + logMin); x2 = Math.pow(10, xAnn2 * delX + logMin); x3 = Math.pow(10, xAnn3 * delX + logMin); } xyplot.addAnnotation(new XYLineAnnotation(x3, y, x2, y, trace.getStroke(), trace.getColor())); XYTextAnnotation xyText = new XYTextAnnotation(trace.getName(), x1, y); xyText.setFont(new Font("Verdana", Font.BOLD, 18)); xyText.setTextAnchor(TextAnchor.CENTER_RIGHT); xyplot.addAnnotation(xyText); } iTrace++; } combinedPlot.add(xyplot, 1); } // panel final JFreeChart chart = new JFreeChart(combinedPlot); chart.setTitle(new TextTitle(plotTitle, new Font("Verdana", Font.BOLD, 18))); chart.removeLegend(); try { ChartUtilities.saveChartAsPNG(outputFile, chart, 1400, 1400); } catch (IOException e) { // System.err.println("Problem occurred creating chart."); logger.error("IOException:", e); } }