Example usage for org.jfree.chart.axis NumberAxis setNumberFormatOverride

List of usage examples for org.jfree.chart.axis NumberAxis setNumberFormatOverride

Introduction

In this page you can find the example usage for org.jfree.chart.axis NumberAxis setNumberFormatOverride.

Prototype

public void setNumberFormatOverride(NumberFormat formatter) 

Source Link

Document

Sets the number format override.

Usage

From source file:de.tor.tribes.ui.views.DSWorkbenchStatsFrame.java

private void setupChart(String pInitialId, XYDataset pInitialDataset) {
    chart = ChartFactory.createTimeSeriesChart("Spielerstatistiken", // title
            "Zeiten", // x-axis label
            pInitialId, // y-axis label
            pInitialDataset, // data
            jShowLegend.isSelected(), // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );//from   ww  w .jav  a2 s.  c  o  m

    chart.setBackgroundPaint(Constants.DS_BACK);
    XYPlot plot = (XYPlot) chart.getPlot();
    setupPlotDrawing(plot);
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    for (int i = 0; i < plot.getSeriesCount(); i++) {
        renderer.setSeriesLinesVisible(i, jShowLines.isSelected());
        renderer.setSeriesShapesVisible(i, jShowDataPoints.isSelected());
        plot.setRenderer(i, renderer);
    }

    renderer.setDefaultItemLabelsVisible(jShowItemValues.isSelected());
    renderer.setDefaultItemLabelGenerator(new org.jfree.chart.labels.StandardXYItemLabelGenerator());
    renderer.setDefaultToolTipGenerator(
            new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                    new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"), NumberFormat.getInstance()));
    int lastDataset = plot.getDatasetCount() - 1;
    if (lastDataset > 0) {
        plot.getRangeAxis().setAxisLinePaint(plot.getLegendItems().get(lastDataset).getLinePaint());
        plot.getRangeAxis().setLabelPaint(plot.getLegendItems().get(lastDataset).getLinePaint());
        plot.getRangeAxis().setTickLabelPaint(plot.getLegendItems().get(lastDataset).getLinePaint());
        plot.getRangeAxis().setTickMarkPaint(plot.getLegendItems().get(lastDataset).getLinePaint());
    }
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(0);
    nf.setMaximumFractionDigits(0);
    NumberAxis na = ((NumberAxis) plot.getRangeAxis());
    if (na != null) {
        na.setNumberFormatOverride(nf);
    }
}

From source file:stockit.Manager.java

private void displayBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_displayBtnActionPerformed
    // TODO add your handling code here:
    //panel.removeAll();

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    int row = table.getSelectedRow();
    if (row != -1) {
        //dataset.setValue(, "", table.getValueAt(0,1).toString());
        String selectedStock = table.getValueAt(row, 0).toString();
        try {//from w  w  w . ja  va2 s  . com
            DBConnection dbcon = new DBConnection();
            dbcon.establishConnection();
            Statement stmt = dbcon.con.createStatement();
            ResultSet rs = stmt
                    .executeQuery("Select stock_daily_performance.Closing_Price, stock_daily_performance.Date\n"
                            + "FROM stock_daily_performance, stock\n"
                            + "WHERE stock_daily_performance.StockID = stock.StockID AND stock.StockID = '"
                            + selectedStock + "'" + "AND Date IN\n" + "( Select * from\n" + "(\n"
                            + "SELECT Date \n" + "FROM stock_daily_performance \n"
                            + "WHERE StockID = stockID \n" + "ORDER BY Date ASC\n" + ") temp_table)\n"
                            + "            ");

            while (rs.next()) {

                String formattedDate = rs.getString("Date");
                int closing_price = rs.getInt("Closing_Price");
                System.out.println("Closing Price: " + closing_price);
                System.out.println("Date: " + formattedDate);
                dataset.setValue(closing_price, "value", formattedDate);

            }
            dbcon.con.close();
        } catch (Exception ex) {
            Logger.getLogger(clientLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
        String stockName = table.getValueAt(row, 1).toString();
        JFreeChart chart = ChartFactory.createBarChart3D(stockName + " Stock Performance", "Date", "Value",
                dataset, PlotOrientation.VERTICAL, false, false, false);
        Color c = new Color(240, 240, 240, 0);
        chart.setBackgroundPaint(c);
        CategoryPlot catPlot = chart.getCategoryPlot();
        catPlot.setRangeGridlinePaint(Color.BLACK);
        //set interval of Y-axis ticks (tick every 5 units)
        NumberAxis yAxis = (NumberAxis) catPlot.getRangeAxis();
        yAxis.setTickUnit(new NumberTickUnit(5));

        //set y-axis labels as currency types ($)
        NumberFormat currency = NumberFormat.getCurrencyInstance();
        yAxis.setNumberFormatOverride(currency);

        //setting number of lines an x-axis label is displayed on
        CategoryAxis categoryAxis = catPlot.getDomainAxis();
        categoryAxis.setMaximumCategoryLabelLines(4);
        panel.setLayout(new java.awt.BorderLayout());
        ChartPanel chartPanel = new ChartPanel(chart);
        panel.removeAll();
        panel.add(chartPanel, BorderLayout.CENTER);
        panel.validate();
        panel.repaint();
    }
}

From source file:de.tor.tribes.ui.views.DSWorkbenchStatsFrame.java

private void addDataset(String pId, XYDataset pDataset) {
    if (chart == null) {
        setupChart(pId, pDataset);//from  w  ww  . j  av  a 2s.  c  om
    } else {
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setDataset(plot.getDatasetCount(), pDataset);
        NumberAxis axis = new NumberAxis(pId);
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(0);
        nf.setMaximumFractionDigits(0);
        axis.setNumberFormatOverride(nf);
        plot.setRangeAxis(plot.getDatasetCount() - 1, axis);
        plot.setRangeAxisLocation(plot.getDatasetCount() - 1, AxisLocation.TOP_OR_LEFT);
        plot.mapDatasetToRangeAxis(plot.getDatasetCount() - 1, plot.getDatasetCount() - 1);
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(0, jShowLines.isSelected());
        renderer.setSeriesShapesVisible(0, jShowDataPoints.isSelected());
        plot.setRenderer(plot.getDatasetCount() - 1, renderer);
        renderer.setDefaultItemLabelsVisible(jShowItemValues.isSelected());
        renderer.setDefaultItemLabelGenerator(new org.jfree.chart.labels.StandardXYItemLabelGenerator());
        renderer.setDefaultToolTipGenerator(
                new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                        new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"), NumberFormat.getInstance()));
        axis.setAxisLinePaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
        axis.setLabelPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
        axis.setTickLabelPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
        axis.setTickMarkPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
    }
}

From source file:de.dmarcini.submatix.pclogger.gui.spx42LogGraphPanel.java

/**
 * Temperaturgraph machen Project: SubmatixBTForPC Package: de.dmarcini.submatix.pclogger.gui
 * //from w  w w .j ava 2  s. c  o  m
 * @author Dirk Marciniak (dirk_marciniak@arcor.de) Stand: 02.08.2012
 * @param labels
 * @param thePlot
 * @param diveList
 */
private void makeTemperatureGraph(Vector<Integer[]> diveList, XYPlot thePlot, String[] labels) {
    XYDataset tempDataSet;
    Color axisColor = new Color(ProjectConst.GRAPH_TEMPERATURE_ACOLOR);
    Color renderColor = new Color(ProjectConst.GRAPH_TEMPERATURE_RCOLOR);
    //
    lg.debug("create temp dataset");
    if (showingUnitSystem == savedUnitSystem || showingUnitSystem == ProjectConst.UNITS_DEFAULT) {
        // Keine nderung norwendig!
        tempDataSet = createXYDataset(LangStrings.getString("spx42LogGraphPanel.graph.tempScalaTitle"),
                diveList, ProjectConst.UNITS_DEFAULT, 0, LogDerbyDatabaseUtil.TEMPERATURE);
    } else {
        // bitte konvertiere die Einheiten ins gewnschte Format!
        tempDataSet = createXYDataset(LangStrings.getString("spx42LogGraphPanel.graph.tempScalaTitle"),
                diveList, showingUnitSystem, 0, LogDerbyDatabaseUtil.TEMPERATURE);
    }
    final XYLineAndShapeRenderer lineTemperatureRenderer = new XYLineAndShapeRenderer(true, true);
    final NumberAxis tempAxis = new NumberAxis(
            LangStrings.getString("spx42LogGraphPanel.graph.tempAxisTitle") + " " + labels[1]);
    tempAxis.setLabelPaint(axisColor);
    tempAxis.setTickLabelPaint(axisColor);
    tempAxis.setNumberFormatOverride(new DecimalFormat("###.##"));
    lineTemperatureRenderer.setSeriesPaint(0, renderColor);
    lineTemperatureRenderer.setSeriesShapesVisible(0, false);
    lineTemperatureRenderer.setDrawSeriesLineAsPath(true);
    tempAxis.setAutoRangeIncludesZero(true);
    thePlot.setRangeAxis(GRAPH_DEPTH, tempAxis);
    thePlot.mapDatasetToRangeAxis(GRAPH_DEPTH, 0);
    thePlot.setDataset(GRAPH_TEMPERATURE, tempDataSet);
    thePlot.setRenderer(GRAPH_TEMPERATURE, lineTemperatureRenderer);
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.XYAreaLineChartExpression.java

protected void configureChart(final JFreeChart chart) {
    super.configureChart(chart);

    final XYPlot plot = chart.getXYPlot();

    if (isSharedRangeAxis() == false) {
        final ValueAxis linesAxis = plot.getRangeAxis(1);
        if (linesAxis instanceof NumberAxis) {
            final NumberAxis numberAxis = (NumberAxis) linesAxis;
            numberAxis.setAutoRangeIncludesZero(isLineAxisIncludesZero());
            numberAxis.setAutoRangeStickyZero(isLineAxisStickyZero());

            if (getLinePeriodCount() > 0) {
                if (getLineTicksLabelFormat() != null) {
                    final FastDecimalFormat formatter = new FastDecimalFormat(getLineTicksLabelFormat(),
                            getResourceBundleFactory().getLocale());
                    numberAxis.setTickUnit(new FastNumberTickUnit(getLinePeriodCount(), formatter));
                } else {
                    numberAxis.setTickUnit(new FastNumberTickUnit(getLinePeriodCount()));
                }//from w w  w.  j  av  a  2 s .c o  m
            } else {
                if (getLineTicksLabelFormat() != null) {
                    final DecimalFormat formatter = new DecimalFormat(getLineTicksLabelFormat(),
                            new DecimalFormatSymbols(getResourceBundleFactory().getLocale()));
                    numberAxis.setNumberFormatOverride(formatter);
                }
            }
        } else if (linesAxis instanceof DateAxis) {
            final DateAxis numberAxis = (DateAxis) linesAxis;

            if (getLinePeriodCount() > 0 && getLineTimePeriod() != null) {
                if (getLineTicksLabelFormat() != null) {
                    final SimpleDateFormat formatter = new SimpleDateFormat(getLineTicksLabelFormat(),
                            new DateFormatSymbols(getResourceBundleFactory().getLocale()));
                    numberAxis.setTickUnit(new DateTickUnit(getDateUnitAsInt(getLineTimePeriod()),
                            (int) getLinePeriodCount(), formatter));
                } else {
                    numberAxis.setTickUnit(new DateTickUnit(getDateUnitAsInt(getLineTimePeriod()),
                            (int) getLinePeriodCount()));
                }
            } else if (getRangeTickFormatString() != null) {
                final SimpleDateFormat formatter = new SimpleDateFormat(getRangeTickFormatString(),
                        new DateFormatSymbols(getResourceBundleFactory().getLocale()));
                numberAxis.setDateFormatOverride(formatter);
            }
        }

        if (linesAxis != null) {
            final Font labelFont = Font.decode(getLabelFont());
            linesAxis.setLabelFont(labelFont);
            linesAxis.setTickLabelFont(labelFont);

            if (getLineTitleFont() != null) {
                linesAxis.setLabelFont(getLineTitleFont());
            }
            if (getLineTickFont() != null) {
                linesAxis.setTickLabelFont(getLineTickFont());
            }
            final int level = getRuntime().getProcessingContext().getCompatibilityLevel();
            if (ClassicEngineBoot.isEnforceCompatibilityFor(level, 3, 8)) {
                final double lineRangeMinimumVal = lineRangeMinimum == null ? 0 : lineRangeMinimum;
                final double lineRangeMaximumVal = lineRangeMaximum == null ? 0 : lineRangeMaximum;
                if (lineRangeMinimum != null) {
                    linesAxis.setLowerBound(getLineRangeMinimum());
                }
                if (lineRangeMaximum != null) {
                    linesAxis.setUpperBound(getRangeMaximum());
                }
                if (lineRangeMinimumVal == 0 && lineRangeMaximumVal == 1) {
                    linesAxis.setLowerBound(0);
                    linesAxis.setUpperBound(1);
                    linesAxis.setAutoRange(true);
                }
            } else {
                if (lineRangeMinimum != null) {
                    linesAxis.setLowerBound(lineRangeMinimum);
                }
                if (lineRangeMaximum != null) {
                    linesAxis.setUpperBound(lineRangeMaximum);
                }
                linesAxis.setAutoRange(isLineAxisAutoRange());
            }
        }
    }

    final XYLineAndShapeRenderer linesRenderer = (XYLineAndShapeRenderer) plot.getRenderer(1);
    if (linesRenderer != null) {
        //set stroke with line width
        linesRenderer.setStroke(translateLineStyle(getLineWidth(), getLineStyle()));
        //hide shapes on line
        linesRenderer.setShapesVisible(isMarkersVisible());
        linesRenderer.setBaseShapesFilled(isMarkersVisible());

        //set colors for each line
        for (int i = 0; i < lineSeriesColor.size(); i++) {
            final String s = (String) lineSeriesColor.get(i);
            linesRenderer.setSeriesPaint(i, parseColorFromString(s));
        }
    }
}

From source file:fr.inria.soctrace.framesoc.ui.histogram.view.HistogramView.java

/**
 * Prepare the plot// w ww . j av a2  s  .  co  m
 * 
 * @param chart
 *            jfreechart chart
 * @param displayed
 *            displayed time interval
 */
private void preparePlot(boolean first, JFreeChart chart, TimeInterval displayed) {
    // Plot customization
    plot = chart.getXYPlot();
    // Grid and background colors
    plot.setBackgroundPaint(BACKGROUND_PAINT);
    plot.setDomainGridlinePaint(DOMAIN_GRIDLINE_PAINT);
    plot.setRangeGridlinePaint(RANGE_GRIDLINE_PAINT);
    // Tooltip
    XYItemRenderer renderer = plot.getRenderer();
    renderer.setBaseToolTipGenerator(TOOLTIP_GENERATOR);
    // Disable bar white stripes
    XYBarRenderer barRenderer = (XYBarRenderer) plot.getRenderer();
    barRenderer.setBarPainter(new StandardXYBarPainter());
    // X axis
    X_FORMAT.setTimeUnit(TimeUnit.getTimeUnit(currentShownTrace.getTimeUnit()));
    X_FORMAT.setContext(displayed.startTimestamp, displayed.endTimestamp, true);
    NumberAxis xaxis = (NumberAxis) plot.getDomainAxis();
    xaxis.setTickLabelFont(TICK_LABEL_FONT);
    xaxis.setLabelFont(LABEL_FONT);
    xaxis.setNumberFormatOverride(X_FORMAT);
    TickDescriptor des = X_FORMAT.getTickDescriptor(displayed.startTimestamp, displayed.endTimestamp,
            numberOfTicks);
    xaxis.setTickUnit(new NumberTickUnit(des.delta));
    xaxis.addChangeListener(new AxisChangeListener() {
        @Override
        public void axisChanged(AxisChangeEvent arg) {
            long max = ((Double) plot.getDomainAxis().getRange().getUpperBound()).longValue();
            long min = ((Double) plot.getDomainAxis().getRange().getLowerBound()).longValue();
            TickDescriptor des = X_FORMAT.getTickDescriptor(min, max, numberOfTicks);
            NumberTickUnit newUnit = new NumberTickUnit(des.delta);
            NumberTickUnit currentUnit = ((NumberAxis) arg.getAxis()).getTickUnit();
            // ensure we don't loop
            if (!currentUnit.equals(newUnit)) {
                ((NumberAxis) arg.getAxis()).setTickUnit(newUnit);
            }
        }
    });
    // Y axis
    NumberAxis yaxis = (NumberAxis) plot.getRangeAxis();
    yaxis.setTickLabelFont(TICK_LABEL_FONT);
    yaxis.setLabelFont(LABEL_FONT);
    // remove the marker, if any
    if (marker != null) {
        plot.removeDomainMarker(marker);
        marker = null;
    }
}

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/*from w ww.  j av a 2  s.c o m*/
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor());
    rangeAxis.setUpperMargin(0.10);
    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:io.github.mzmine.modules.plots.msspectrum.MsSpectrumPlotWindowController.java

public void initialize() {

    final JFreeChart chart = chartNode.getChart();
    final XYPlot plot = chart.getXYPlot();

    // Do not set colors and strokes dynamically. They are instead provided
    // by the dataset and configured in configureRenderer()
    plot.setDrawingSupplier(null);/*from ww  w . j a  va 2 s . c o  m*/
    plot.setDomainGridlinePaint(JavaFXUtil.convertColorToAWT(gridColor));
    plot.setRangeGridlinePaint(JavaFXUtil.convertColorToAWT(gridColor));
    plot.setBackgroundPaint(JavaFXUtil.convertColorToAWT(backgroundColor));
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    plot.setDomainCrosshairVisible(false);
    plot.setRangeCrosshairVisible(false);

    // chart properties
    chart.setBackgroundPaint(JavaFXUtil.convertColorToAWT(backgroundColor));

    // legend properties
    LegendTitle legend = chart.getLegend();
    // legend.setItemFont(legendFont);
    legend.setFrame(BlockBorder.NONE);

    // set the X axis (m/z) properties
    NumberAxis xAxis = (NumberAxis) plot.getDomainAxis();
    xAxis.setLabel("m/z");
    xAxis.setUpperMargin(0.03);
    xAxis.setLowerMargin(0.03);
    xAxis.setRangeType(RangeType.POSITIVE);
    xAxis.setTickLabelInsets(new RectangleInsets(0, 0, 20, 20));

    // set the Y axis (intensity) properties
    NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
    yAxis.setLabel("Intensity");
    yAxis.setRangeType(RangeType.POSITIVE);
    yAxis.setAutoRangeIncludesZero(true);

    // set the fixed number formats, because otherwise JFreeChart sometimes
    // shows exponent, sometimes it doesn't
    DecimalFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();
    xAxis.setNumberFormatOverride(mzFormat);
    DecimalFormat intensityFormat = MZmineCore.getConfiguration().getIntensityFormat();
    yAxis.setNumberFormatOverride(intensityFormat);

    chartTitle = chartNode.getChart().getTitle();
    chartTitle.setMargin(5, 0, 0, 0);
    chartTitle.setFont(titleFont);

    chartNode.setCursor(Cursor.CROSSHAIR);

    // Remove the dataset if it is removed from the list
    datasets.addListener((Change<? extends MsSpectrumDataSet> c) -> {
        while (c.next()) {
            if (c.wasRemoved()) {
                for (MsSpectrumDataSet ds : c.getRemoved()) {
                    int index = plot.indexOf(ds);
                    plot.setDataset(index, null);
                }
            }
        }
    });

    itemLabelsVisible.addListener((prop, oldVal, newVal) -> {
        for (MsSpectrumDataSet dataset : datasets) {
            int datasetIndex = plot.indexOf(dataset);
            XYItemRenderer renderer = plot.getRenderer(datasetIndex);
            renderer.setBaseItemLabelsVisible(newVal);
        }
    });

    legendVisible.addListener((prop, oldVal, newVal) -> {
        legend.setVisible(newVal);
    });

}

From source file:de.dmarcini.submatix.pclogger.gui.spx42LogGraphPanel.java

/**
 * Zeichne die eigentliche Grafik Project: SubmatixBTForPC Package: de.dmarcini.submatix.pclogger.gui
 * /*from  ww w  . jav  a2  s  .  co  m*/
 * @author Dirk Marciniak (dirk_marciniak@arcor.de) Stand: 03.07.2012
 * @param dbId
 *          dbid in Tabelle D_TABLE_DIVEDETAIL
 * @param device
 */
private void makeGraphForLog(int dbId, String device) {
    Vector<Integer[]> diveList;
    Vector<String> diluents;
    int[] headData;
    XYPlot thePlot;
    JFreeChart logChart;
    int min, sec;
    // das alte Zeug entsorgen
    releaseGraph();
    //
    // Daten eines TG lesen
    //
    lg.debug("read dive log from DB...");
    diveList = databaseUtil.getDiveDataFromIdLog(dbId);
    if (diveList == null || diveList.isEmpty()) {
        return;
    }
    //
    // verwendete Diluents finden
    //
    diluents = getDiluentNamesFromDive(diveList);
    // Anzeigen
    String diluentString = StringUtils.join(diluents, ", ");
    diluentLabel.setText(
            String.format(LangStrings.getString("spx42LogGraphPanel.diluentLabel.text"), diluentString));
    lg.debug(diluents);
    //
    // Labels fr Tachgangseckdaten fllen
    //
    headData = databaseUtil.getHeadDiveDataFromIdLog(dbId);
    notesLabel.setText(databaseUtil.getNotesForIdLog(dbId));
    showingUnitSystem = SpxPcloggerProgramConfig.unitsProperty;
    savedUnitSystem = headData[6];
    // jetzt die Strings fr Masseinheiten holen
    String[] labels = getUnitsLabel(showingUnitSystem, savedUnitSystem);
    depthUnitName = labels[0];
    tempUnitName = labels[1];
    pressureUnitName = labels[2];
    //
    // entscheide ob etwas umgerechnet werden sollte
    //
    if (showingUnitSystem == savedUnitSystem || showingUnitSystem == ProjectConst.UNITS_DEFAULT) {
        // nein, alles schick
        maxDepthValueLabel.setText(String.format(maxDepthLabelString, (headData[3] / 10.0), depthUnitName));
        coldestTempValueLabel.setText(String.format(coldestLabelString, (headData[2] / 10.0), tempUnitName));
    } else {
        // umrechnen!
        if (showingUnitSystem == ProjectConst.UNITS_IMPERIAL) {
            // metrisch-> imperial konvertieren
            // 1 foot == 30,48 cm == 0.3048 Meter
            maxDepthValueLabel
                    .setText(String.format(maxDepthLabelString, (headData[3] / 10.0) / 0.3048, depthUnitName));
            // t F = 5?9 (t  32) C
            coldestTempValueLabel.setText(
                    String.format(coldestLabelString, (5.0 / 9.0) * ((headData[2] / 10.0) - 32), tempUnitName));
        } else {
            maxDepthValueLabel
                    .setText(String.format(maxDepthLabelString, (headData[3] / 10.0) * 0.3048, depthUnitName));
            // t C = (9?5 t + 32) F
            coldestTempValueLabel.setText(
                    String.format(coldestLabelString, ((9.0 / 5.0) * (headData[2] / 10.0)) + 32, tempUnitName));
        }
    }
    min = headData[5] / 60;
    sec = headData[5] % 60;
    diveLenValueLabel.setText(String.format(diveLenLabelString, min, sec, "min"));
    //
    // einen Plot machen (Grundlage des Diagramms)
    //
    lg.debug("create graph...");
    thePlot = new XYPlot();
    //
    // Eigenschaften definieren
    //
    thePlot.setBackgroundPaint(Color.lightGray);
    thePlot.setDomainGridlinesVisible(true);
    thePlot.setDomainGridlinePaint(Color.white);
    thePlot.setRangeGridlinesVisible(true);
    thePlot.setRangeGridlinePaint(Color.white);
    thePlot.setDomainPannable(true);
    thePlot.setRangePannable(false);
    //
    // ein Chart zur Anzeige in einem Panel erzeugen
    //
    logChart = new JFreeChart(LangStrings.getString("spx42LogGraphPanel.graph.chartTitle"), thePlot);
    logChart.setAntiAlias(true);
    logChart.addSubtitle(new TextTitle(LangStrings.getString("spx42LogGraphPanel.graph.chartSubTitle")));
    // ein Thema zufgen, damit ich eigene Farben einbauen kann
    ChartUtilities.applyCurrentTheme(logChart);
    //
    // ein Diagramm-Panel erzeugen
    //
    chartPanel = new ChartPanel(logChart);
    chartPanel.setMouseZoomable(true);
    chartPanel.setAutoscrolls(true);
    chartPanel.setMouseWheelEnabled(true);
    chartPanel.setRangeZoomable(false);
    chartPanel.setDisplayToolTips(false);
    chartPanel.setZoomTriggerDistance(10);
    add(chartPanel, BorderLayout.CENTER);
    //
    // Datumsachse umformatieren
    //
    final NumberAxis axis = new NumberAxis(LangStrings.getString("spx42LogGraphPanel.graph.dateAxisTitle"));
    MinuteFormatter formatter = new MinuteFormatter(
            LangStrings.getString("spx42LogGraphPanel.graph.dateAxisUnit"));
    axis.setNumberFormatOverride(formatter);
    thePlot.setDomainAxis(axis);
    //
    // Temperatur einfgen
    //
    if (SpxPcloggerProgramConfig.showTemperature) {
        makeTemperatureGraph(diveList, thePlot, labels);
    }
    //
    // Partialdruck einfgen
    // die Achse erst mal machen
    final NumberAxis ppo2Axis = new NumberAxis(
            LangStrings.getString("spx42LogGraphPanel.graph.ppo2AxisTitle") + " " + pressureUnitName);
    final NumberAxis percentAxis = new NumberAxis(LangStrings.getString("spx42LogGraphPanel.graph.inertgas"));
    //
    // wenn eine der Achsen dargesstellt werden muss, dann sollte die Achse auch in der Grafil da sein
    //
    if (SpxPcloggerProgramConfig.showPpo01 || SpxPcloggerProgramConfig.showPpo02
            || SpxPcloggerProgramConfig.showPpo03 || SpxPcloggerProgramConfig.showPpoResult
            || SpxPcloggerProgramConfig.showSetpoint) {
        ppo2Axis.setAutoRangeIncludesZero(false);
        ppo2Axis.setAutoRange(false);
        //
        // wie skaliere ich die Achse?
        //
        if (showingUnitSystem == ProjectConst.UNITS_DEFAULT) {
            // so wie gespeichert
            if (savedUnitSystem == ProjectConst.UNITS_METRIC) {
                ppo2Axis.setRange(0.0, 3.5);
            } else {
                ppo2Axis.setRange(0.0, (3.5 * 14.504));
            }
        } else if (showingUnitSystem == ProjectConst.UNITS_METRIC) {
            ppo2Axis.setRange(0.0, 3.5);
        } else {
            ppo2Axis.setRange(0.0, (3.5 * 14.504));
        }
        ppo2Axis.setLabelPaint(new Color(ProjectConst.GRAPH_PPO2ALL_ACOLOR));
        ppo2Axis.setTickLabelPaint(new Color(ProjectConst.GRAPH_PPO2ALL_ACOLOR));
        thePlot.setRangeAxis(GRAPH_PPO2ALL, ppo2Axis);
    }
    if (SpxPcloggerProgramConfig.showHe || SpxPcloggerProgramConfig.showN2) {
        percentAxis.setAutoRangeIncludesZero(false);
        percentAxis.setAutoRange(false);
        percentAxis.setRange(0.0, 100.0);
        percentAxis.setLabelPaint(new Color(ProjectConst.GRAPH_INNERTGAS_ACOLOR));
        percentAxis.setTickLabelPaint(new Color(ProjectConst.GRAPH_INNERTGAS_ACOLOR));
        thePlot.setRangeAxis(GRAPH_HE, percentAxis);
    }
    //
    // Partialdrcke der einzelnen Sensoren einfgen
    //
    // Sensor 01 anzeigen
    if (SpxPcloggerProgramConfig.showPpo01) {
        makePpoGraph(diveList, thePlot, 1);
    }
    // Sensor 02 anzeigen
    if (SpxPcloggerProgramConfig.showPpo02) {
        makePpoGraph(diveList, thePlot, 2);
    }
    // Sensor 03 anzeigen
    if (SpxPcloggerProgramConfig.showPpo03) {
        makePpoGraph(diveList, thePlot, 3);
    }
    // Resultierenden PPO anzeigen
    if (SpxPcloggerProgramConfig.showPpoResult) {
        makePpoGraph(diveList, thePlot, 0);
        // makePpoResultGraph( diveList, thePlot );
    }
    if (SpxPcloggerProgramConfig.showSetpoint) {
        makeSetpointGraph(diveList, thePlot);
    }
    //
    // Helium und Stickstoffanteil im Gas?
    //
    if (SpxPcloggerProgramConfig.showHe) {
        makeInnertGasGraph(diveList, thePlot, "he");
    }
    if (SpxPcloggerProgramConfig.showN2) {
        makeInnertGasGraph(diveList, thePlot, "n2");
    }
    //
    // die Nullzeit auf Wunsch
    //
    if (SpxPcloggerProgramConfig.showNulltime) {
        makeNulltimeGraph(diveList, thePlot);
    }
    //
    // die Tiefe einfgen
    //
    makeDepthGraph(diveList, thePlot);
    //
    showingDbIdForDiveWasShowing = dbId;
    lg.debug("create graph...OK");
}