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

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

Introduction

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

Prototype

public void setLabelFont(Font font) 

Source Link

Document

Sets the font for the axis label and sends an AxisChangeEvent to all registered listeners.

Usage

From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.OverlaidBarLine.java

public JFreeChart createChart(DatasetMap datasets) {
    logger.debug("IN");

    // create the first renderer...

    CategoryPlot plot = new CategoryPlot();

    NumberFormat nf = NumberFormat.getNumberInstance(locale);

    NumberAxis rangeAxis = new NumberAxis(getValueLabel());
    rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setLabelPaint(styleXaxesLabels.getColor());
    rangeAxis/*from  www  . jav  a2s .  c  om*/
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor());
    //      rangeAxis.setLowerBound(600);
    //      rangeAxis.setUpperBound(720);
    if (firstAxisLB != null && firstAxisUB != null) {
        rangeAxis.setLowerBound(firstAxisLB);
        rangeAxis.setUpperBound(firstAxisUB);
    }

    rangeAxis.setUpperMargin(0.10);
    plot.setRangeAxis(0, rangeAxis);
    if (rangeIntegerValues == true) {
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }
    rangeAxis.setNumberFormatOverride(nf);

    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);

    DefaultCategoryDataset datasetLineFirstAxis = (DefaultCategoryDataset) datasets.getDatasets().get("1-line");
    DefaultCategoryDataset datasetBarFirstAxis = (DefaultCategoryDataset) datasets.getDatasets().get("1-bar");
    DefaultCategoryDataset datasetLineSecondAxis = (DefaultCategoryDataset) datasets.getDatasets()
            .get("2-line");
    DefaultCategoryDataset datasetBarSecondAxis = (DefaultCategoryDataset) datasets.getDatasets().get("2-bar");

    //I create one bar renderer and one line
    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());
    }

    if (useBars) {

        CategoryItemRenderer barRenderer = null;
        if (stackedBarRenderer_1 == true) {
            barRenderer = new StackedBarRenderer();
        } else {
            barRenderer = new BarRenderer();
        }

        CategoryItemRenderer barRenderer2 = new BarRenderer();

        if (stackedBarRenderer_2 == true) {
            barRenderer2 = new StackedBarRenderer();
        } else {
            barRenderer2 = new BarRenderer();
        }

        if (maxBarWidth != null) {
            ((BarRenderer) barRenderer).setMaximumBarWidth(maxBarWidth.doubleValue());
            ((BarRenderer) barRenderer2).setMaximumBarWidth(maxBarWidth.doubleValue());
        }

        if (showValueLabels) {
            barRenderer.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
            barRenderer.setBaseItemLabelsVisible(true);
            barRenderer.setBaseItemLabelFont(
                    new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
            barRenderer.setBaseItemLabelPaint(styleValueLabels.getColor());

            //            barRenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
            //                  ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
            //
            //            barRenderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(
            //                  ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));

            if (valueLabelsPosition.equalsIgnoreCase("inside")) {
                barRenderer.setBasePositiveItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
                barRenderer.setBaseNegativeItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
            } else {
                barRenderer.setBasePositiveItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
                barRenderer.setBaseNegativeItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
            }

        } else if (additionalLabels) {
            barRenderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());
            barRenderer.setBaseItemLabelGenerator(generator);
            double orient = (-Math.PI / 2.0);
            if (styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) {
                orient = 0.0;
            }

            barRenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));
            barRenderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));
            barRenderer.setBaseItemLabelFont(
                    new Font(defaultLabelsStyle.getFontName(), Font.PLAIN, defaultLabelsStyle.getSize()));
            barRenderer.setBaseItemLabelPaint(defaultLabelsStyle.getColor());
            barRenderer.setBaseItemLabelsVisible(true);
        }

        if (showValueLabels) {
            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));

            if (valueLabelsPosition.equalsIgnoreCase("inside")) {
                barRenderer2.setBasePositiveItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
                barRenderer2.setBaseNegativeItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
            } else {
                barRenderer2.setBasePositiveItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
                barRenderer2.setBaseNegativeItemLabelPosition(
                        new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
            }

        } else if (additionalLabels) {
            barRenderer2.setBaseItemLabelGenerator(generator);
            double orient = (-Math.PI / 2.0);
            if (styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) {
                orient = 0.0;
            }

            barRenderer2.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));
            barRenderer2.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER,
                    TextAnchor.CENTER, TextAnchor.CENTER, orient));

            barRenderer2.setBaseItemLabelFont(
                    new Font(defaultLabelsStyle.getFontName(), Font.PLAIN, defaultLabelsStyle.getSize()));
            barRenderer2.setBaseItemLabelPaint(defaultLabelsStyle.getColor());
            barRenderer2.setBaseItemLabelsVisible(true);

        }

        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) {
                    barRenderer.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);
                    /* test con un renderer
                    if (idx > index){
                       index = idx+1;
                    }
                            
                    barRenderer.setSeriesPaint(index, color);*/
                }
            }
        }
        // add tooltip if enabled
        if (enableToolTips) {
            MyCategoryToolTipGenerator generatorToolTip = new MyCategoryToolTipGenerator(freeToolTips,
                    seriesTooltip, categoriesTooltip, seriesCaptions);
            barRenderer.setToolTipGenerator(generatorToolTip);
            barRenderer2.setToolTipGenerator(generatorToolTip);
        }
        //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
                && (!mycatUrl.getCategoryUrlLabel().equals("") || !mycatUrl.getSerieUrlLabel().equals(""))) {
            barRenderer.setItemURLGenerator(mycatUrl);
            barRenderer2.setItemURLGenerator(mycatUrl);
        }

        plot.setDataset(2, datasetBarFirstAxis);
        plot.setDataset(3, datasetBarSecondAxis);

        plot.setRenderer(2, barRenderer);
        plot.setRenderer(3, barRenderer2);

    }

    if (useLines) {

        LineAndShapeRenderer lineRenderer = new LineAndShapeRenderer();
        LineAndShapeRenderer lineRenderer2 = new LineAndShapeRenderer();

        //lineRenderer.setShapesFilled(false);
        lineRenderer.setShapesFilled(true);
        lineRenderer2.setShapesFilled(true);

        // 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) {
                lineRenderer.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);
            }
        }

        if (enableToolTips) {
            MyCategoryToolTipGenerator generatorToolTip = new MyCategoryToolTipGenerator(freeToolTips,
                    seriesTooltip, categoriesTooltip, seriesCaptions);
            lineRenderer.setToolTipGenerator(generatorToolTip);
            lineRenderer2.setToolTipGenerator(generatorToolTip);
        }

        if (showValueLabels) {
            lineRenderer.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
            lineRenderer.setBaseItemLabelsVisible(true);
            lineRenderer.setBaseItemLabelFont(
                    new Font(styleValueLabels.getFontName(), Font.ITALIC, styleValueLabels.getSize()));
            lineRenderer.setBaseItemLabelPaint(styleValueLabels.getColor());

            lineRenderer.setBasePositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_RIGHT));

            lineRenderer.setBaseNegativeItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_RIGHT));

        } else if (additionalLabels) {
            lineRenderer.setBaseItemLabelGenerator(generator);
            lineRenderer.setBaseItemLabelFont(
                    new Font(defaultLabelsStyle.getFontName(), Font.PLAIN, defaultLabelsStyle.getSize()));
            lineRenderer.setBaseItemLabelPaint(defaultLabelsStyle.getColor());
            lineRenderer.setBaseItemLabelsVisible(true);
        }

        if (showValueLabels) {
            lineRenderer2.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
            lineRenderer2.setBaseItemLabelsVisible(true);
            lineRenderer2.setBaseItemLabelFont(
                    new Font(styleValueLabels.getFontName(), Font.ITALIC, styleValueLabels.getSize()));
            lineRenderer2.setBaseItemLabelPaint(styleValueLabels.getColor());

            lineRenderer2.setBasePositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_RIGHT));

            lineRenderer2.setBaseNegativeItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_RIGHT));

        } else if (additionalLabels) {
            lineRenderer2.setBaseItemLabelGenerator(generator);
            lineRenderer2.setBaseItemLabelFont(
                    new Font(defaultLabelsStyle.getFontName(), Font.PLAIN, defaultLabelsStyle.getSize()));
            lineRenderer2.setBaseItemLabelPaint(defaultLabelsStyle.getColor());
            lineRenderer2.setBaseItemLabelsVisible(true);
        }

        //         DefaultCategoryDataset datasetSecondAxis=(DefaultCategoryDataset)datasets.getDatasets().get("2");

        if (colorMap != null) {
            for (Iterator iterator = datasetLineSecondAxis.getRowKeys().iterator(); iterator.hasNext();) {
                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);
                }
            }
            for (Iterator iterator = datasetLineFirstAxis.getRowKeys().iterator(); iterator.hasNext();) {
                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) {
                    lineRenderer.setSeriesPaint(index, color);
                }
            }

        }
        plot.setDataset(0, datasetLineFirstAxis);
        plot.setRenderer(0, lineRenderer);
        plot.setDataset(1, datasetLineSecondAxis);
        plot.setRenderer(1, lineRenderer2);

    }

    if (secondAxis) {
        NumberAxis na = new NumberAxis(secondAxisLabel);
        na.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
        na.setLabelPaint(styleXaxesLabels.getColor());
        na.setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
        na.setTickLabelPaint(styleXaxesLabels.getColor());
        na.setUpperMargin(0.10);
        na.setNumberFormatOverride(nf);
        //         rangeAxis.setLowerBound(270);
        //         rangeAxis.setUpperBound(340);
        if (secondAxisLB != null && secondAxisUB != null) {
            rangeAxis.setLowerBound(secondAxisLB);
            rangeAxis.setUpperBound(secondAxisUB);
        }
        plot.setRangeAxis(1, na);
        plot.mapDatasetToRangeAxis(0, 0);
        plot.mapDatasetToRangeAxis(2, 0);
        plot.mapDatasetToRangeAxis(1, 1);
        plot.mapDatasetToRangeAxis(3, 1);
        if (rangeIntegerValues == true) {
            na.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        }

    }

    //plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
    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);

    if (legend == true)
        drawLegend(chart);

    logger.debug("OUT");

    return chart;

}

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;/* w w w .  j ava2s  .  co  m*/
    }

    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:com.intel.stl.ui.common.view.ComponentFactory.java

public static JFreeChart createStackedXYBarChart(XYDataset dataset, String title, String domainAxisLabel,
        String rangeAxisLabel, boolean legend) {
    DateAxis dateaxis = new DateAxis(domainAxisLabel);
    NumberAxis numberaxis = new NumberAxis(rangeAxisLabel);
    StackedXYBarRenderer stackedxybarrenderer = new StackedXYBarRenderer(0.10000000000000001D);
    XYPlot xyplot = new XYPlot(dataset, dateaxis, numberaxis, stackedxybarrenderer);
    JFreeChart jfreechart = new JFreeChart(title, UIConstants.H5_FONT, xyplot, legend);
    ChartUtilities.applyCurrentTheme(jfreechart);

    stackedxybarrenderer.setShadowVisible(false);
    stackedxybarrenderer.setDrawBarOutline(false);
    stackedxybarrenderer.setBarPainter(new StandardXYBarPainter());
    stackedxybarrenderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator(
            "<html><b>{0}</b><br> Time: {1}<br> Data: {2}</html>", Util.getHHMMSS(), new DecimalFormat("###")));

    xyplot.setBackgroundPaint(null);/*w  ww. j  a  va2s. c  om*/
    xyplot.setOutlinePaint(null);
    xyplot.setRangeGridlinePaint(UIConstants.INTEL_BORDER_GRAY);

    dateaxis.setLabelFont(UIConstants.H5_FONT);
    dateaxis.setLowerMargin(0.0D);
    dateaxis.setUpperMargin(0.0D);

    numberaxis.setRangeType(RangeType.POSITIVE);
    numberaxis.setLabelFont(UIConstants.H5_FONT);
    numberaxis.setLabelInsets(new RectangleInsets(0, 0, 0, 0));
    numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    return jfreechart;
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.StackedBar.java

/**
 * Inherited by IChart.// ww  w  .  java2  s.  com
 * 
 * @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("Taken Dataset");

    logger.debug("Get plot orientaton");
    PlotOrientation plotOrientation = PlotOrientation.VERTICAL;
    if (horizontalView) {
        plotOrientation = PlotOrientation.HORIZONTAL;
    }

    logger.debug("Call Chart Creation");
    JFreeChart chart = ChartFactory.createStackedBarChart(name, // chart title
            categoryLabel, // domain axis label
            valueLabel, // range axis label
            dataset, // data
            plotOrientation, // the plot orientation
            false, // legend
            true, // tooltips
            false // urls
    );
    logger.debug("Chart Created");

    chart.setBackgroundPaint(Color.white);
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(color);
    plot.setRangeGridlinePaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setDomainGridlinesVisible(true);

    logger.debug("set renderer");
    StackedBarRenderer renderer = (StackedBarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);
    renderer.setBaseItemLabelsVisible(true);

    if (percentageValue)
        renderer.setBaseItemLabelGenerator(
                new StandardCategoryItemLabelGenerator("{2}", new DecimalFormat("#,##.#%")));
    else if (makePercentage)
        renderer.setRenderAsPercentages(true);

    /*
    else
       renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
     */
    renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());

    if (maxBarWidth != null) {
        renderer.setMaximumBarWidth(maxBarWidth.doubleValue());
    }

    boolean document_composition = false;
    if (mode.equalsIgnoreCase(SpagoBIConstants.DOCUMENT_COMPOSITION))
        document_composition = true;

    logger.debug("Calling Url Generation");

    MyCategoryUrlGenerator mycatUrl = null;
    if (rootUrl != null) {
        logger.debug("Set MycatUrl");
        mycatUrl = new MyCategoryUrlGenerator(rootUrl);

        mycatUrl.setDocument_composition(document_composition);
        mycatUrl.setCategoryUrlLabel(categoryUrlName);
        mycatUrl.setSerieUrlLabel(serieUrlname);
    }
    if (mycatUrl != null)
        renderer.setItemURLGenerator(mycatUrl);

    logger.debug("Text Title");

    TextTitle title = setStyleTitle(name, styleTitle);
    chart.setTitle(title);
    if (subName != null && !subName.equals("")) {
        TextTitle subTitle = setStyleTitle(subName, styleSubTitle);
        chart.addSubtitle(subTitle);
    }

    logger.debug("Style Labels");

    Color colorSubInvisibleTitle = Color.decode("#FFFFFF");
    StyleLabel styleSubSubTitle = new StyleLabel("Arial", 12, colorSubInvisibleTitle);
    TextTitle subsubTitle = setStyleTitle("", styleSubSubTitle);
    chart.addSubtitle(subsubTitle);
    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

    // set the background color for the chart...
    chart.setBackgroundPaint(color);

    logger.debug("Axis creation");
    // set the range axis to display integers only...

    NumberFormat nf = NumberFormat.getNumberInstance(locale);

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    if (makePercentage)
        rangeAxis.setNumberFormatOverride(NumberFormat.getPercentInstance());
    else
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    if (rangeIntegerValues == true) {
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }

    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 (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);
        }
    }

    renderer.setDrawBarOutline(false);

    logger.debug("Set series color");

    int seriesN = dataset.getRowCount();
    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) {
        for (int i = 0; i < seriesN; i++) {
            String serieName = (String) dataset.getRowKey(i);

            // if serie has been rinominated I must search with the new name!
            String nameToSearchWith = (seriesLabelsMap != null && seriesLabelsMap.containsKey(serieName))
                    ? seriesLabelsMap.get(serieName).toString()
                    : serieName;

            Color color = (Color) colorMap.get(nameToSearchWith);
            if (color != null) {
                renderer.setSeriesPaint(i, color);
                renderer.setSeriesItemLabelFont(i,
                        new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
            }
        }
    }

    logger.debug("If cumulative set series paint " + cumulative);

    if (cumulative) {
        int row = dataset.getRowIndex("CUMULATIVE");
        if (row != -1) {
            if (color != null)
                renderer.setSeriesPaint(row, color);
            else
                renderer.setSeriesPaint(row, Color.WHITE);
        }
    }

    MyStandardCategoryItemLabelGenerator generator = null;
    logger.debug("Are there addition labels " + additionalLabels);
    logger.debug("Are there value labels " + showValueLabels);

    if (showValueLabels) {
        renderer.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
        renderer.setBaseItemLabelsVisible(true);
        renderer.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        renderer.setBaseItemLabelPaint(styleValueLabels.getColor());

        if (valueLabelsPosition.equalsIgnoreCase("inside")) {
            renderer.setBasePositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
            renderer.setBaseNegativeItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
        } else {
            renderer.setBasePositiveItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.BASELINE_LEFT));
            renderer.setBaseNegativeItemLabelPosition(
                    new ItemLabelPosition(ItemLabelAnchor.OUTSIDE3, TextAnchor.BASELINE_LEFT));
        }
    } else if (additionalLabels) {

        generator = new MyStandardCategoryItemLabelGenerator(catSerLabels, "{1}", NumberFormat.getInstance());
        logger.debug("generator set");

        double orient = (-Math.PI / 2.0);
        logger.debug("add labels style");
        if (styleValueLabels.getOrientation() != null
                && styleValueLabels.getOrientation().equalsIgnoreCase("horizontal")) {
            orient = 0.0;
        }
        renderer.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        renderer.setBaseItemLabelPaint(styleValueLabels.getColor());

        logger.debug("add labels style set");

        renderer.setBaseItemLabelGenerator(generator);
        renderer.setBaseItemLabelsVisible(true);
        //vertical labels          
        renderer.setBasePositiveItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER, TextAnchor.CENTER, orient));
        renderer.setBaseNegativeItemLabelPosition(
                new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER, TextAnchor.CENTER, orient));

        logger.debug("end of add labels ");

    }

    logger.debug("domain axis");

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 4.0));
    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());
    //opacizzazione colori
    if (!cumulative)
        plot.setForegroundAlpha(0.6f);
    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);/*www. ja va2  s .com*/
        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);
    }

}

From source file:org.pentaho.chart.plugin.jfreechart.JFreeChartFactoryEngine.java

private void initXYPlot(JFreeChart chart, ChartModel chartModel) {
    initPlot(chart, chartModel);//from w w w .  j a  v  a2 s  .  c  om

    org.pentaho.chart.model.TwoAxisPlot twoAxisPlot = (org.pentaho.chart.model.TwoAxisPlot) chartModel
            .getPlot();
    XYPlot xyPlot = chart.getXYPlot();

    List<Integer> colors = getPlotColors(twoAxisPlot);

    for (int i = 0; i < colors.size(); i++) {
        for (int j = 0; j < xyPlot.getDatasetCount(); j++) {
            xyPlot.getRenderer(j).setSeriesPaint(i, new Color(0x00FFFFFF & colors.get(i)));
        }
    }

    Font domainAxisFont = ChartUtils.getFont(twoAxisPlot.getDomainAxis().getFontFamily(),
            twoAxisPlot.getDomainAxis().getFontStyle(), twoAxisPlot.getDomainAxis().getFontWeight(),
            twoAxisPlot.getDomainAxis().getFontSize());
    Font rangeAxisFont = ChartUtils.getFont(twoAxisPlot.getRangeAxis().getFontFamily(),
            twoAxisPlot.getRangeAxis().getFontStyle(), twoAxisPlot.getRangeAxis().getFontWeight(),
            twoAxisPlot.getRangeAxis().getFontSize());
    Font rangeTitleFont = ChartUtils.getFont(twoAxisPlot.getRangeAxis().getLegend().getFontFamily(),
            twoAxisPlot.getRangeAxis().getLegend().getFontStyle(),
            twoAxisPlot.getRangeAxis().getLegend().getFontWeight(),
            twoAxisPlot.getRangeAxis().getLegend().getFontSize());
    Font domainTitleFont = ChartUtils.getFont(twoAxisPlot.getDomainAxis().getLegend().getFontFamily(),
            twoAxisPlot.getDomainAxis().getLegend().getFontStyle(),
            twoAxisPlot.getDomainAxis().getLegend().getFontWeight(),
            twoAxisPlot.getDomainAxis().getLegend().getFontSize());

    NumberAxis domainAxis = (NumberAxis) xyPlot.getDomainAxis();
    NumberAxis rangeAxis = (NumberAxis) xyPlot.getRangeAxis();

    domainAxis.setAutoRangeIncludesZero(true);
    rangeAxis.setAutoRangeIncludesZero(true);

    AxesLabels axesLabels = getAxesLabels(chartModel);
    if ((axesLabels.rangeAxisLabel.length() > 0) && (rangeTitleFont != null)) {
        rangeAxis.setLabelFont(rangeTitleFont);
    }

    if ((axesLabels.domainAxisLabel.length() > 0) && (domainTitleFont != null)) {
        domainAxis.setLabelFont(domainTitleFont);
    }

    domainAxis.setVerticalTickLabels(
            twoAxisPlot.getHorizontalAxis().getLabelOrientation() == LabelOrientation.VERTICAL);

    if (domainAxisFont != null) {
        domainAxis.setTickLabelFont(domainAxisFont);
    }
    if (rangeAxisFont != null) {
        rangeAxis.setTickLabelFont(rangeAxisFont);
    }

    Number rangeMin = ((NumericAxis) twoAxisPlot.getRangeAxis()).getMinValue();
    if (rangeMin != null) {
        rangeAxis.setLowerBound(rangeMin.doubleValue());
    }
    Number rangeMax = ((NumericAxis) twoAxisPlot.getRangeAxis()).getMaxValue();
    if (rangeMax != null) {
        rangeAxis.setUpperBound(rangeMax.doubleValue());
    }
}

From source file:com.chart.SwingChart.java

/**
 * Add axis//from   ww w . j a va  2 s.c  o  m
 * @param name new axis name 
 */
@Override
public final void addAxis(String name) {
    boolean encontrado = false;
    for (AxisChart categoria : axes) {
        if (categoria.getName().equals(name)) {
            encontrado = true;
            break;
        }
    }
    if (!encontrado) {
        axes.add(new AxisChart((name)));
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    NumberAxis ejeOrdenada = new NumberAxis(name);

    ejeOrdenada.setLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
    ejeOrdenada.setTickLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
    ejeOrdenada.setLabelFont(ejeOrdenada.getLabelFont().deriveFont(fontSize));
    ejeOrdenada.setTickLabelFont(ejeOrdenada.getLabelFont().deriveFont(fontSize));

    int i = datasetList.size();

    datasetList.add(dataset);
    AxesList.add(ejeOrdenada);
    plot.setDataset(i, dataset);
    plot.setRangeAxis(i, ejeOrdenada);
    plot.setRangeAxisLocation(i, AxisLocation.BOTTOM_OR_LEFT);
    plot.mapDatasetToRangeAxis(i, i);
    XYItemRenderer renderer = new XYLineAndShapeRenderer(true, true);
    if (i == 0) {
        plot.setRenderer(renderer);
    } else {
        plot.setRenderer(i, renderer);
    }

    final LegendAxis le;
    final int indiceLeyenda = legendFrame.getChildren().size();

    legendFrame.getChildren().add(le = new LegendAxis(name));

    le.setOnMouseClicked((MouseEvent t) -> {
        if (le.selected && t.getClickCount() == 2) {
            setOrdinateRange(AxesList.get(indiceLeyenda));
        }
    });

    le.setOnMouseEntered((MouseEvent t) -> {
        le.setStyle("-fx-background-color:blue");
        le.selected = true;
        AxesList.get(indiceLeyenda).setLabelPaint(scene2awtColor(javafx.scene.paint.Color.web("blue")));
        AxesList.get(indiceLeyenda).setTickLabelPaint(scene2awtColor(javafx.scene.paint.Color.web("blue")));
    });

    le.setOnMouseExited((MouseEvent t) -> {
        le.setStyle("-fx-background-color:" + strBackgroundColor);
        le.selected = false;
        AxesList.get(indiceLeyenda).setLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
        AxesList.get(indiceLeyenda)
                .setTickLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
    });
}

From source file:com.chart.SwingChart.java

/**
 * Background edition//  w ww.j a  va 2s  .c o m
 */
final public void backgroundEdition() {
    final ColorPicker colorPickerChartBackground = new ColorPicker(
            javafx.scene.paint.Color.web(strChartBackgroundColor));
    colorPickerChartBackground.setMaxWidth(Double.MAX_VALUE);
    final ColorPicker colorPickerGridline = new ColorPicker(javafx.scene.paint.Color.web(strGridlineColor));
    colorPickerGridline.setMaxWidth(Double.MAX_VALUE);
    final ColorPicker colorPickerBackground = new ColorPicker(javafx.scene.paint.Color.web(strBackgroundColor));
    colorPickerBackground.setMaxWidth(Double.MAX_VALUE);
    final ColorPicker colorPickerTick = new ColorPicker(javafx.scene.paint.Color.web(strTickColor));
    colorPickerTick.setMaxWidth(Double.MAX_VALUE);
    final TextField tfFontSize = new TextField();
    tfFontSize.setMaxWidth(Double.MAX_VALUE);

    GridPane grid = new GridPane();
    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(0, 10, 0, 10));

    grid.add(new Label("Background color"), 0, 0);
    grid.add(colorPickerChartBackground, 1, 0);
    grid.add(new Label("Gridline color"), 0, 1);
    grid.add(colorPickerGridline, 1, 1);
    grid.add(new Label("Frame color"), 0, 2);
    grid.add(colorPickerBackground, 1, 2);
    grid.add(new Label("Tick color"), 0, 3);
    grid.add(colorPickerTick, 1, 3);
    grid.add(new Label("Font size"), 0, 4);
    grid.add(tfFontSize, 1, 4);
    tfFontSize.setText(String.valueOf(fontSize));

    new PseudoModalDialog(skeleton, grid, true) {

        @Override
        public boolean validation() {
            fontSize = Float.valueOf(tfFontSize.getText().replace(",", "."));
            strBackgroundColor = colorPickerBackground.getValue().toString().replace("0x", "#");
            for (Node le : legendFrame.getChildren()) {
                if (le instanceof LegendAxis) {
                    le.setStyle("-fx-background-color:" + strBackgroundColor);
                    ((LegendAxis) le).selected = false;
                }
            }
            chart.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)));
            chartPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4),
                    BorderFactory.createLineBorder(
                            scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)))));
            chartPanel.setBackground(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor)));

            legendFrame.setStyle("marco: " + colorPickerBackground.getValue().toString().replace("0x", "#")
                    + ";-fx-background-color: marco;");

            strChartBackgroundColor = colorPickerChartBackground.getValue().toString().replace("0x", "#");
            plot.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strChartBackgroundColor)));

            for (Node le : legendFrame.getChildren()) {
                if (le instanceof LegendAxis) {
                    le.setStyle("-fx-background-color:" + strBackgroundColor);
                    ((LegendAxis) le).selected = false;
                    for (Node nn : ((LegendAxis) le).getChildren()) {
                        if (nn instanceof Label) {
                            ((Label) nn).setStyle("fondo: "
                                    + colorPickerChartBackground.getValue().toString().replace("0x", "#")
                                    + ";-fx-background-color: fondo;-fx-text-fill: ladder(fondo, white 49%, black 50%);-fx-padding:5px;-fx-background-radius: 5;-fx-font-size: "
                                    + String.valueOf(fontSize) + "px");
                        }
                    }
                }
            }

            strGridlineColor = colorPickerGridline.getValue().toString().replace("0x", "#");
            plot.setDomainGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor)));
            plot.setRangeGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor)));

            strTickColor = colorPickerTick.getValue().toString().replace("0x", "#");
            abcissaAxis.setLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
            abcissaAxis.setTickLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
            abcissaAxis.setLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize));
            abcissaAxis.setTickLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize));

            for (NumberAxis ejeOrdenada : AxesList) {
                ejeOrdenada.setLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
                ejeOrdenada.setTickLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor)));
                ejeOrdenada.setLabelFont(ejeOrdenada.getLabelFont().deriveFont(fontSize));
                ejeOrdenada.setTickLabelFont(ejeOrdenada.getLabelFont().deriveFont(fontSize));
            }
            return true;
        }
    }.show();

}

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

/**
 * Prepare the plot//from  w  w w .j  ava 2 s.  c o  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:msi.gama.outputs.layers.ChartLayerStatement.java

private void createBars(final IScope scope) {
    final CategoryPlot plot = (CategoryPlot) chart.getPlot();
    BarRenderer renderer = new CustomRenderer();
    plot.setRenderer(renderer);//from  ww w  . j  av  a 2 s .  c  om

    dataset = new DefaultCategoryDataset();
    int i = 0;
    for (final ChartData e : datas) {
        // String legend = e.getName();
        // ((DefaultCategoryDataset) dataset).setValue(0d, new Integer(0), legend/* , legend */);

        final String legend = e.getName();
        if (!CategoryItemRenderer.class.isInstance(e.getRenderer())) {
            e.renderer = new CustomRenderer();
        }
        plot.setRenderer(i, (CategoryItemRenderer) e.getRenderer(), false);
        final Color c = e.getColor();
        plot.getRenderer(i).setSeriesPaint(0, c);
        // plot.setDataset(i, (DefaultCategoryDataset) dataset);
        i++;
        history.append(legend);
        history.append(',');

    }
    if (history.length() > 0) {
        history.deleteCharAt(history.length() - 1);
    }
    history.append(Strings.LN);
    plot.setDataset((DefaultCategoryDataset) dataset);

    chart.removeLegend();
    final NumberAxis yAxis = (NumberAxis) plot.getRangeAxis();
    yAxis.setTickLabelFont(getTickFont());
    yAxis.setLabelFont(getLabelFont());
    IExpression expr = getFacet(YRANGE);
    IExpression expr2 = getFacet(YTICKUNIT);
    if (expr != null) {
        Object range = expr.value(scope);
        // Double range = Cast.asFloat(scope, expr.value(scope));

        if (range instanceof Number) {
            double r = ((Number) range).doubleValue();
            if (r > 0) {
                yAxis.setFixedAutoRange(r);
                yAxis.setAutoRangeMinimumSize(r);
            }
            // yAxis.setAutoRangeIncludesZero(false);
        } else if (range instanceof GamaPoint) {
            yAxis.setRange(((GamaPoint) range).getX(), ((GamaPoint) range).getY());
        }
    }
    if (expr2 != null) {
        Object range = expr2.value(scope);
        // Double range = Cast.asFloat(scope, expr.value(scope));

        if (range instanceof Number) {
            double r = ((Number) range).doubleValue();
            if (r > 0) {
                yAxis.setTickUnit(new NumberTickUnit(r));
            }
        }
    }

    final CategoryAxis axis = plot.getDomainAxis();
    Double gap = Cast.asFloat(scope, getFacetValue(scope, IKeyword.GAP, 0.01));
    // ((BarRenderer) plot.getRenderer()).setItemMargin(gap);
    renderer.setMaximumBarWidth(1 - gap);
    axis.setCategoryMargin(gap);
    axis.setUpperMargin(gap);
    axis.setLowerMargin(gap);

}