Example usage for org.jfree.chart.axis CategoryAxis setUpperMargin

List of usage examples for org.jfree.chart.axis CategoryAxis setUpperMargin

Introduction

In this page you can find the example usage for org.jfree.chart.axis CategoryAxis setUpperMargin.

Prototype

public void setUpperMargin(double margin) 

Source Link

Document

Sets the upper margin for the axis and sends an AxisChangeEvent to all registered listeners.

Usage

From source file:weka.gui.beans.JFreeChartOffscreenChartRenderer.java

/**
 * Render histogram(s) (numeric attribute) or bar chart (nominal attribute).
 * Some implementations may not be able to render more than one histogram/bar
 * on the same chart - the implementation can either throw an exception or
 * just process the first series in this case.
 * //from   www.j a va 2 s.  c  om
 * @param width the width of the resulting chart in pixels
 * @param height the height of the resulting chart in pixels
 * @param series a list of Instances - one for each series to be plotted
 * @param attsToPlot the attribute to plot corresponding to the Instances in
 *          the series list
 * @param optionalArgs optional arguments to the renderer (may be null)
 * 
 * @return a BufferedImage containing the chart
 * @throws Exception if there is a problem rendering the chart
 */
public BufferedImage renderHistogram(int width, int height, List<Instances> series, String attToPlot,
        List<String> additionalArgs) throws Exception {

    String plotTitle = "Bar Chart";
    String userTitle = getOption(additionalArgs, "-title");
    plotTitle = (userTitle != null) ? userTitle : plotTitle;
    String colorAtt = getOption(additionalArgs, "-color");
    String pareto = getOption(additionalArgs, "-pareto");

    boolean doPareto = false;
    if (pareto != null && pareto.length() == 0 && series.size() == 1) {
        doPareto = true;
    }

    if (series.size() == 1 && colorAtt != null && colorAtt.length() > 0) {
        int colIndex = getIndexOfAttribute(series.get(0), colorAtt);

        if (colIndex >= 0 && series.get(0).attribute(colIndex).isNominal() && !doPareto) {
            // split single series out into multiple instances objects - one
            // per class
            series = splitToClasses(series.get(0), colIndex);
            for (Instances insts : series) {
                insts.setClassIndex(colIndex);
            }
        }
    }

    Instances masterInstances = series.get(0);
    int attIndex = getIndexOfAttribute(masterInstances, attToPlot);
    if (attIndex < 0) {
        attIndex = 0;
    }

    if (!(series.get(0).attribute(attIndex).isNominal()
            || series.get(0).attribute(attIndex).isRelationValued())) {
        doPareto = false;
    }

    // Do a pareto chart
    if (doPareto) {
        final DefaultKeyedValues data = new DefaultKeyedValues();
        AttributeStats attStats = masterInstances.attributeStats(attIndex);
        double[] attValFreqs = attStats.nominalWeights;
        for (int i = 0; i < attValFreqs.length; i++) {
            Number freq = new Double(attValFreqs[i]);
            data.addValue(masterInstances.attribute(attIndex).value(i), freq);
        }

        data.sortByValues(SortOrder.DESCENDING);
        final KeyedValues cumulative = DataUtilities.getCumulativePercentages(data);
        final CategoryDataset dataset = DatasetUtilities
                .createCategoryDataset(masterInstances.attribute(attIndex).name(), data);

        final JFreeChart chart = ChartFactory.createBarChart(plotTitle,
                masterInstances.attribute(attIndex).name(), "Fequency/weight mass", dataset,
                PlotOrientation.VERTICAL, true, false, false);

        final CategoryPlot plot = chart.getCategoryPlot();

        final CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setLowerMargin(0.02);
        domainAxis.setUpperMargin(0.02);

        LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();
        CategoryDataset dataset2 = DatasetUtilities.createCategoryDataset("Cumulative", cumulative);
        final NumberAxis axis2 = new NumberAxis("Percent");
        axis2.setNumberFormatOverride(NumberFormat.getPercentInstance());
        // plot.
        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, dataset2);
        plot.setRenderer(1, renderer2);
        plot.mapDatasetToRangeAxis(1, 1);
        plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

        chart.setBackgroundPaint(java.awt.Color.white);
        BufferedImage image = chart.createBufferedImage(width, height);
        return image;
    }

    boolean seriesAreClasses = false;
    int classIndex = masterInstances.classIndex();

    if (classIndex >= 0 && !masterInstances.attribute(classIndex).isNumeric()
            && !masterInstances.attribute(classIndex).isRelationValued()
            && masterInstances.attributeStats(classIndex).distinctCount == 1) {
        // series correspond to class labels (assume that subsequent series only
        // contain instances of one class)...
        seriesAreClasses = true;
    }

    // bar chart for a nominal attribute
    if (masterInstances.attribute(attIndex).isNominal() || masterInstances.attribute(attIndex).isString()) {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();

        // do the master series
        String masterSeriesTitle = masterInstances.relationName();
        if (seriesAreClasses) {
            for (int i = 0; i < masterInstances.numInstances(); i++) {
                Instance current = masterInstances.instance(i);
                if (!current.isMissing(classIndex)) {
                    masterSeriesTitle = current.stringValue(classIndex);
                    break;
                }
            }
        }

        AttributeStats attStats = masterInstances.attributeStats(attIndex);
        double[] attValFreqs = attStats.nominalWeights;
        for (int i = 0; i < attValFreqs.length; i++) {
            Number freq = new Double(attValFreqs[i]);
            dataset.addValue(freq, masterSeriesTitle, masterInstances.attribute(attIndex).value(i));
        }

        // any subsequent series
        for (int i = 1; i < series.size(); i++) {
            Instances nextSeries = series.get(i);

            String seriesTitle = nextSeries.relationName();

            if (seriesAreClasses) {
                for (int j = 0; j < nextSeries.numInstances(); j++) {
                    Instance current = nextSeries.instance(j);
                    if (!current.isMissing(classIndex)) {
                        seriesTitle = current.stringValue(classIndex);
                        break;
                    }
                }

                attStats = nextSeries.attributeStats(attIndex);
                attValFreqs = attStats.nominalWeights;
                for (int j = 0; j < attValFreqs.length; j++) {
                    Number freq = new Double(attValFreqs[j]);
                    dataset.addValue(freq, seriesTitle, nextSeries.attribute(attIndex).value(j));
                }
            }
        }

        JFreeChart chart = null;

        if (series.size() == 1) {
            chart = ChartFactory.createBarChart(plotTitle, masterInstances.attribute(attIndex).name(),
                    "Fequency/weight mass", dataset, PlotOrientation.VERTICAL, true, false, false);
        } else {
            chart = ChartFactory.createStackedBarChart(plotTitle, masterInstances.attribute(attIndex).name(),
                    "Fequency/weight mass", dataset, PlotOrientation.VERTICAL, true, false, false);
        }

        chart.setBackgroundPaint(java.awt.Color.white);
        BufferedImage image = chart.createBufferedImage(width, height);
        return image;

    } else {
        // histogram for numeric attributes
        HistogramDataset dataset = new HistogramDataset();

        // combine all series in order to get overall std dev, and range
        Instances temp = new Instances(masterInstances);
        for (int i = 1; i < series.size(); i++) {
            Instances additional = series.get(i);
            for (Instance tempI : additional) {
                temp.add(tempI);
            }
        }

        AttributeStats stats = temp.attributeStats(attIndex);
        Stats numericStats = stats.numericStats;
        double intervalWidth = 3.49 * numericStats.stdDev * StrictMath.pow(temp.numInstances(), (-1.0 / 3.0));
        double range = numericStats.max - numericStats.min;
        int numBins = StrictMath.max(1, (int) StrictMath.round(range / intervalWidth));

        // do the master series
        String masterSeriesTitle = masterInstances.relationName();
        if (seriesAreClasses) {
            for (int i = 0; i < masterInstances.numInstances(); i++) {
                Instance current = masterInstances.instance(i);
                if (!current.isMissing(current.classAttribute())) {
                    masterSeriesTitle = current.stringValue(current.classAttribute());
                    break;
                }
            }
        }

        // have to set min, max and num bins (using heuristic from AttSummPanel).
        // Make sure
        // to set series length to num instances - num missing values for att
        stats = masterInstances.attributeStats(attIndex);
        /*
         * numericStats = stats.numericStats; //numericStats.calculateDerived();
         * intervalWidth = StrictMath.max(1, 3.49 * numericStats.stdDev *
         * StrictMath.pow(masterInstances.numInstances(), (-1.0/3.0)));
         */

        double[] seriesVals = new double[masterInstances.numInstances() - stats.missingCount];
        int count = 0;
        for (int i = 0; i < masterInstances.numInstances(); i++) {
            Instance current = masterInstances.instance(i);
            if (!current.isMissing(attIndex)) {
                seriesVals[count++] = current.value(attIndex);
            }
        }

        dataset.addSeries(masterSeriesTitle, seriesVals, numBins, numericStats.min, numericStats.max);

        // any subsequent series
        for (int i = 1; i < series.size(); i++) {
            Instances nextSeries = series.get(i);

            String seriesTitle = nextSeries.relationName();

            if (seriesAreClasses) {
                for (int j = 0; j < nextSeries.numInstances(); j++) {
                    Instance current = nextSeries.instance(j);
                    if (!current.isMissing(nextSeries.classAttribute())) {
                        seriesTitle = current.stringValue(nextSeries.classAttribute());
                        break;
                    }
                }
            }

            stats = nextSeries.attributeStats(attIndex);
            /*
             * numericStats = stats.numericStats; //
             * numericStats.calculateDerived(); intervalWidth = StrictMath.max(1,
             * 3.49 * numericStats.stdDev *
             * StrictMath.pow(masterInstances.numInstances(), (-1.0/3.0))); range =
             * numericStats.max - numericStats.min; numBins = StrictMath.max(1,
             * (int) StrictMath.round(range / intervalWidth));
             */
            seriesVals = new double[nextSeries.numInstances() - stats.missingCount];
            count = 0;
            for (int j = 0; j < nextSeries.numInstances(); j++) {
                Instance current = nextSeries.instance(j);
                if (!current.isMissing(attIndex)) {
                    seriesVals[count++] = current.value(attIndex);
                }
            }

            dataset.addSeries(seriesTitle, seriesVals, numBins, numericStats.min, numericStats.max);
        }

        JFreeChart chart = ChartFactory.createHistogram(plotTitle, masterInstances.attribute(attIndex).name(),
                null, dataset, PlotOrientation.VERTICAL, true, false, false);

        // chart.setBackgroundPaint(java.awt.Color.white);
        XYPlot xyplot = (XYPlot) chart.getPlot();
        xyplot.setForegroundAlpha(0.50F);
        XYBarRenderer xybarrenderer = (XYBarRenderer) xyplot.getRenderer();
        xybarrenderer.setDrawBarOutline(false);
        xybarrenderer.setShadowVisible(false);

        BufferedImage image = chart.createBufferedImage(width, height);
        return image;
    }
}

From source file:edu.jhuapl.graphs.jfreechart.JFreeChartCategoryGraphSource.java

@Override
public void initialize() throws GraphException {
    String title = getParam(GraphSource.GRAPH_TITLE, String.class, DEFAULT_TITLE);
    String xLabel = getParam(GraphSource.GRAPH_X_LABEL, String.class, DEFAULT_DOMAIN_LABEL);
    String yLabel = getParam(GraphSource.GRAPH_Y_LABEL, String.class, DEFAULT_RANGE_LABEL);
    CategoryDataset dataset = makeDataSet();

    chart = createChart(title, xLabel, yLabel, dataset, false, false);

    // start customizing the graph
    Paint backgroundColor = getParam(GraphSource.BACKGROUND_COLOR, Paint.class, DEFAULT_BACKGROUND_COLOR);
    Paint plotColor = getParam(JFreeChartTimeSeriesGraphSource.PLOT_COLOR, Paint.class, backgroundColor);
    Double offset = getParam(GraphSource.AXIS_OFFSET, Double.class, DEFAULT_AXIS_OFFSET);
    Paint graphDomainGridlinePaint = getParam(GraphSource.GRAPH_DOMAIN_GRIDLINE_PAINT, Paint.class,
            backgroundColor);//from   w  w  w  . j av  a 2 s. com
    Paint graphRangeGridlinePaint = getParam(GraphSource.GRAPH_RANGE_GRIDLINE_PAINT, Paint.class,
            backgroundColor);
    boolean graphBorder = getParam(GraphSource.GRAPH_BORDER, Boolean.class, DEFAULT_GRAPH_BORDER);

    chart.setBackgroundPaint(backgroundColor);
    CategoryPlot plot = chart.getCategoryPlot();
    plot.setBackgroundPaint(plotColor);
    plot.setAxisOffset(new RectangleInsets(offset, offset, offset, offset));
    plot.setDomainGridlinePaint(graphDomainGridlinePaint);
    plot.setDomainGridlinesVisible(true);
    plot.setRangeGridlinePaint(graphRangeGridlinePaint);
    plot.setOutlineVisible(graphBorder);

    // set the axis location
    AxisLocation axisLocation = getParam(GraphSource.GRAPH_RANGE_AXIS_LOCATION, AxisLocation.class,
            AxisLocation.TOP_OR_LEFT);
    plot.setRangeAxisLocation(axisLocation);

    // customize the y-axis
    if (params.get(RANGE_AXIS) instanceof ValueAxis) {
        ValueAxis valueAxis = (ValueAxis) params.get(RANGE_AXIS);
        plot.setRangeAxis(valueAxis);
    }

    ValueAxis valueAxis = plot.getRangeAxis();
    Object yAxisFont = params.get(GraphSource.GRAPH_Y_AXIS_FONT);
    Object yAxisLabelFont = params.get(GraphSource.GRAPH_Y_AXIS_LABEL_FONT);
    Double rangeLowerBound = getParam(GraphSource.GRAPH_RANGE_LOWER_BOUND, Double.class, null);
    Double rangeUpperBound = getParam(GraphSource.GRAPH_RANGE_UPPER_BOUND, Double.class, null);
    boolean graphRangeIntegerTick = getParam(GraphSource.GRAPH_RANGE_INTEGER_TICK, Boolean.class, false);
    boolean graphRangeMinorTickVisible = getParam(GraphSource.GRAPH_RANGE_MINOR_TICK_VISIBLE, Boolean.class,
            true);

    if (yAxisFont instanceof Font) {
        valueAxis.setTickLabelFont((Font) yAxisFont);
    }

    if (yAxisLabelFont instanceof Font) {
        valueAxis.setLabelFont((Font) yAxisLabelFont);
    }

    if (rangeLowerBound != null) {
        valueAxis.setLowerBound(rangeLowerBound);
    }

    if (rangeUpperBound != null) {
        valueAxis.setUpperBound(rangeUpperBound);
    }

    if (graphRangeIntegerTick) {
        valueAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    }

    valueAxis.setMinorTickMarksVisible(graphRangeMinorTickVisible);

    // customize the x-axis
    if (params.get(DOMAIN_AXIS) instanceof CategoryAxis) {
        CategoryAxis domainAxis = (CategoryAxis) params.get(DOMAIN_AXIS);
        plot.setDomainAxis(domainAxis);
    }

    CategoryAxis domainAxis = plot.getDomainAxis();
    Object xAxisFont = params.get(GraphSource.GRAPH_X_AXIS_FONT);
    Object xAxisLabelFont = params.get(GraphSource.GRAPH_X_AXIS_LABEL_FONT);

    if (xAxisFont instanceof Font) {
        domainAxis.setTickLabelFont((Font) xAxisFont);
    }

    if (xAxisLabelFont instanceof Font) {
        domainAxis.setLabelFont((Font) xAxisLabelFont);
    }

    domainAxis.setLabel(xLabel);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    plot.setDomainAxis(domainAxis);

    // change the font of the graph title
    Font titleFont = getParam(GraphSource.GRAPH_FONT, Font.class, DEFAULT_GRAPH_TITLE_FONT);
    TextTitle textTitle = new TextTitle();
    textTitle.setText(title);
    textTitle.setFont(titleFont);
    chart.setTitle(textTitle);

    // makes a wrapper for the legend to remove the border around it
    boolean legend = getParam(GraphSource.GRAPH_LEGEND, Boolean.class, DEFAULT_GRAPH_LEGEND);
    boolean legendBorder = getParam(GraphSource.LEGEND_BORDER, Boolean.class, DEFAULT_LEGEND_BORDER);
    Object legendFont = params.get(GraphSource.LEGEND_FONT);

    if (legend) {
        LegendTitle legendTitle = new LegendTitle(chart.getPlot());
        BlockContainer wrapper = new BlockContainer(new BorderArrangement());

        if (legendBorder) {
            wrapper.setFrame(new BlockBorder(1, 1, 1, 1));
        } else {
            wrapper.setFrame(new BlockBorder(0, 0, 0, 0));
        }

        BlockContainer items = legendTitle.getItemContainer();
        items.setPadding(2, 10, 5, 2);
        wrapper.add(items);
        legendTitle.setWrapper(wrapper);
        legendTitle.setPosition(RectangleEdge.BOTTOM);
        legendTitle.setHorizontalAlignment(HorizontalAlignment.CENTER);

        if (legendFont instanceof Font) {
            legendTitle.setItemFont((Font) legendFont);
        }

        chart.addSubtitle(legendTitle);
    }

    this.initialized = true;
}

From source file:hudson.plugins.plot.PlotData.java

/**
 * Generates the plot and stores it in the plot instance variable.
 * /*from w  ww.  jav a2s.c  om*/
 * @param forceGenerate if true, force the plot to be re-generated
 *        even if the on-disk data hasn't changed
 */
private void generatePlot(boolean forceGenerate) {
    class Label implements Comparable<Label> {
        final private Integer buildNum;
        final private String buildDate;
        final private String text;

        public Label(String buildNum, String buildTime, String text) {
            this.buildNum = Integer.parseInt(buildNum);
            synchronized (DATE_FORMAT) {
                this.buildDate = DATE_FORMAT.format(new Date(Long.parseLong(buildTime)));
            }
            this.text = text;
        }

        public int compareTo(Label that) {
            return this.buildNum - that.buildNum;
        }

        @Override
        public boolean equals(Object o) {
            return o instanceof Label && ((Label) o).buildNum.equals(buildNum);
        }

        @Override
        public int hashCode() {
            return buildNum.hashCode();
        }

        public String numDateString() {
            return "#" + buildNum + " (" + buildDate + ")";
        }

        @Override
        public String toString() {
            return text != null ? text : numDateString();
        }
    }
    LOGGER.fine("Generating plot from file: " + csvFilePath.getName());
    PlotCategoryDataset dataset = new PlotCategoryDataset();
    for (String[] record : rawPlotData) {
        // record: series y-value, series label, build number, build date, url
        int buildNum;
        try {
            buildNum = Integer.valueOf(record[2]);
            if (project.getBuildByNumber(buildNum) == null || buildNum > getRightBuildNum()) {
                continue; // skip this record
            }
        } catch (NumberFormatException nfe) {
            continue; // skip this record all together
        }
        Number value = null;
        try {
            value = Integer.valueOf(record[0]);
        } catch (NumberFormatException nfe) {
            try {
                value = Double.valueOf(record[0]);
            } catch (NumberFormatException nfe2) {
                continue; // skip this record all together
            }
        }
        String series = record[1];
        Label xlabel = getUrlUseDescr() ? new Label(record[2], record[3], descriptionForBuild(buildNum))
                : new Label(record[2], record[3], getBuildName(buildNum));
        String url = null;
        if (record.length >= 5)
            url = record[4];
        dataset.setValue(value, url, series, xlabel);
    }
    int numBuilds;
    try {
        numBuilds = Integer.parseInt(getURLNumBuilds());
    } catch (NumberFormatException nfe) {
        numBuilds = DEFAULT_NUMBUILDS;
    }
    dataset.clipDataset(numBuilds);
    plot = createChart(dataset);
    CategoryPlot categoryPlot = (CategoryPlot) plot.getPlot();
    categoryPlot.setDomainGridlinePaint(Color.black);
    categoryPlot.setRangeGridlinePaint(Color.black);
    categoryPlot.setDrawingSupplier(PlotData.supplier);
    CategoryAxis domainAxis = new ShiftedCategoryAxis(Messages.Plot_Build());
    categoryPlot.setDomainAxis(domainAxis);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.03);
    domainAxis.setCategoryMargin(0.0);
    for (Object category : dataset.getColumnKeys()) {
        Label label = (Label) category;
        if (label.text != null) {
            domainAxis.addCategoryLabelToolTip(label, label.numDateString());
        } else {
            domainAxis.addCategoryLabelToolTip(label, descriptionForBuild(label.buildNum));
        }
    }

    AbstractCategoryItemRenderer renderer = (AbstractCategoryItemRenderer) categoryPlot.getRenderer();
    int numColors = dataset.getRowCount();
    for (int i = 0; i < numColors; i++) {
        renderer.setSeriesPaint(i, new Color(Color.HSBtoRGB((1f / numColors) * i, 1f, 1f)));
    }
    renderer.setStroke(new BasicStroke(2.0f));
    renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator(Messages.Plot_Build() + " {1}: {2}",
            NumberFormat.getInstance()));
    renderer.setItemURLGenerator(new PointURLGenerator());
    if (renderer instanceof LineAndShapeRenderer) {
        LineAndShapeRenderer lasRenderer = (LineAndShapeRenderer) renderer;
        lasRenderer.setShapesVisible(true); // TODO: deprecated, may be unnecessary
    }
}

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

public JFreeChart createChart(DatasetMap datasets) {
    logger.debug("IN");
    CategoryDataset dataset = (CategoryDataset) datasets.getDatasets().get("1");

    PlotOrientation plotOrientation = PlotOrientation.VERTICAL;
    if (horizontalView) {
        plotOrientation = PlotOrientation.HORIZONTAL;
    }/*from  ww  w  .ja va 2 s  . com*/

    JFreeChart chart = ChartFactory.createBarChart(name, // chart title
            categoryLabel, // domain axis label
            valueLabel, // range axis label
            dataset, // data
            plotOrientation, // orientation
            false, // include legend
            true, // tooltips?
            false // URLs?
    );

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

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

    // get a reference to the plot for further customisation...
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setDomainGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.white);

    NumberFormat nf = NumberFormat.getNumberInstance(locale);

    // set the range axis to display integers only...
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setLabelPaint(styleXaxesLabels.getColor());
    rangeAxis
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor());
    rangeAxis.setUpperMargin(0.10);
    rangeAxis.setNumberFormatOverride(nf);

    if (firstAxisLB != null && firstAxisUB != null) {
        rangeAxis.setLowerBound(firstAxisLB);
        rangeAxis.setUpperBound(firstAxisUB);
    }

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

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

    // disable bar outlines...
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);

    // add
    CategorySeriesLabelGenerator generator = new StandardCategorySeriesLabelGenerator("{0}");
    renderer.setLegendItemLabelGenerator(generator);

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

    if (showValueLabels) {
        renderer.setBaseItemLabelsVisible(true);
        renderer.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
        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));
        //         }

    }

    // PROVA LEGENDA      
    if (legend == true) {

        drawLegend(chart);

        /*BlockContainer wrapper = new BlockContainer(new BorderArrangement());
        wrapper.setFrame(new BlockBorder(1.0, 1.0, 1.0, 1.0));
                
        LabelBlock titleBlock = new LabelBlock("Legend Items:",
              new Font("SansSerif", Font.BOLD, 12));
        title.setPadding(5, 5, 5, 5);
        wrapper.add(titleBlock, RectangleEdge.TOP);
                
        LegendTitle legend = new LegendTitle(chart.getPlot());
        BlockContainer items = legend.getItemContainer();
        items.setPadding(2, 10, 5, 2);
        wrapper.add(items);
        legend.setWrapper(wrapper);
                
        if(legendPosition.equalsIgnoreCase("bottom")) legend.setPosition(RectangleEdge.BOTTOM);
        else if(legendPosition.equalsIgnoreCase("left")) legend.setPosition(RectangleEdge.LEFT);
        else if(legendPosition.equalsIgnoreCase("right")) legend.setPosition(RectangleEdge.RIGHT);
        else if(legendPosition.equalsIgnoreCase("top")) legend.setPosition(RectangleEdge.TOP);
        else legend.setPosition(RectangleEdge.BOTTOM);
                
        legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
        chart.addSubtitle(legend);*/
    }

    int seriesN = dataset.getRowCount();

    // the order color vedctor overrides the color map!!

    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) {
        logger.debug("color serie by SERIES_COLORS template specification");
        for (int i = 0; i < seriesN; i++) {
            String serieName = (String) dataset.getRowKey(i);
            String labelName = "";
            int index = -1;
            if (seriesCaptions != null && seriesCaptions.size() > 0) {
                labelName = serieName;
                serieName = (String) seriesCaptions.get(serieName);
                index = dataset.getRowIndex(labelName);
            } else
                index = dataset.getRowIndex(serieName);

            Color color = (Color) colorMap.get(serieName);
            if (color != null) {
                //renderer.setSeriesPaint(i, color);
                renderer.setSeriesPaint(index, color);
                renderer.setSeriesItemLabelFont(i,
                        new Font(defaultLabelsStyle.getFontName(), Font.PLAIN, defaultLabelsStyle.getSize()));
                renderer.setSeriesItemLabelPaint(i, defaultLabelsStyle.getColor());
            }
        }
    }

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.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());
    domainAxis.setUpperMargin(0.10);
    logger.debug("OUT");
    return chart;

}

From source file:ca.myewb.frame.servlet.GraphServlet.java

private JFreeChart getChapterPareto(DefaultKeyedValues data, String title, String quantity, String range) {

    JFreeChart chart;/*from ww w .j  a va2 s .com*/

    data.sortByValues(SortOrder.DESCENDING);
    KeyedValues cummulative = DataUtilities.getCumulativePercentages(data);
    CategoryDataset dataset = DatasetUtilities.createCategoryDataset(quantity, data);

    // create the chart...
    chart = ChartFactory.createBarChart(title, // chart title
            "Chapter", // domain axis label
            range, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, true, // include legend
            true, false);

    CategoryPlot plot = chart.getCategoryPlot();

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setLowerMargin(0.02);
    domainAxis.setUpperMargin(0.02);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);

    // set the range axis to display integers only...
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();

    CategoryDataset dataset2 = DatasetUtilities.createCategoryDataset("Cummulative", cummulative);
    NumberAxis axis2 = new NumberAxis("Percent");
    axis2.setNumberFormatOverride(NumberFormat.getPercentInstance());
    axis2.setUpperBound(1);
    axis2.setLowerBound(0);
    plot.setRangeAxis(1, axis2);
    plot.setDataset(1, dataset2);
    plot.setRenderer(1, renderer2);
    plot.mapDatasetToRangeAxis(1, 1);
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

    return chart;
}

From source file:nl.strohalm.cyclos.controls.reports.statistics.graphs.ChartPostProcessorImpl.java

/**
 * This method sets the width of the bars, and the spacing between the bars. It sets a general, hard coded standard for this. In JFreeChart, you
 * cannot set the bar width. In stead, you set the gaps: - lowerMargin is the gap between the start of the x-axis and the first bar - upperMargin
 * is the gap between the end of the x-axis and the last bar - categoryMargin is the gap between the categories. Note that the number you provide
 * here, is divided over all the gaps. So if you set this margin to 0.5 (is 50%) and there are 6 categories, this means that there are 5 gaps, so
 * each gap will get 10%. - itemMargin is the gap between the bars within a category. Again, this number is divided over all the itemgaps in the
 * whole graph. The method also takes care that extreme cases (with a very small amount of bars) still look acceptable.
 * @param plot/*from w  w  w.  j ava2s  . c o m*/
 */
private void setMargins(final CategoryPlot plot) {
    final CategoryAxis axis = plot.getDomainAxis();
    axis.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 9));
    final int categoryCount = plot.getCategories().size();
    final int seriesCount = plot.getDataset().getRowCount();
    axis.setCategoryMargin(0.23); // sets spacing between categories on x%
    // set spacing between bars inside a catgory (in fractions, so 1 = 100%)
    final BarRenderer renderer = (BarRenderer) plot.getRenderer();
    if (categoryCount == 1) {
        renderer.setItemMargin(0.15);
    } else {
        renderer.setItemMargin(0.03);
    }
    // extreme cases
    if (categoryCount * seriesCount < 4) {
        final double outerMargins = (4.0 - (categoryCount * seriesCount)) / 10.0;
        axis.setLowerMargin(outerMargins);
        axis.setUpperMargin(outerMargins);
    }
}

From source file:edu.ucla.stat.SOCR.chart.demo.BoxAndWhiskerChartDemo1.java

/**
 * Creates a sample chart.//from w  w w .  ja  va  2  s .c o  m
 * 
 * @param dataset  the dataset.
 * 
 * @return The chart.
 */
protected JFreeChart createChart(BoxAndWhiskerCategoryDataset dataset) {

    CategoryAxis domainAxis = new CategoryAxis(null);
    NumberAxis rangeAxis = new NumberAxis(rangeLabel);
    BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
    CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
    JFreeChart chart = new JFreeChart(chartTitle, plot);

    chart.setBackgroundPaint(Color.white);

    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setDomainGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.white);

    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    renderer.setLegendItemLabelGenerator(
            new SOCRCategoryCellLabelGenerator(dataset, values_storage, SERIES_COUNT, CATEGORY_COUNT));

    //RowCount -- serie count
    if (dataset.getColumnCount() * dataset.getRowCount() < 5) {

        domainAxis.setLowerMargin(0.2);
        domainAxis.setUpperMargin(0.2);
        if (dataset.getColumnCount() == 1)
            renderer.setItemMargin(0.5);
        //   domainAxis.setCategoryMargin(domainAxis.getCategoryMargin()*2);
        /*         
        System.out.println("1lowerMargin="+domainAxis.getLowerMargin());
        System.out.println("ItemMargin="+renderer.getItemMargin());
        System.out.println("CategoryMargin="+domainAxis.getCategoryMargin());*/

    }

    else if (dataset.getColumnCount() * dataset.getRowCount() < 10) {
        domainAxis.setLowerMargin(domainAxis.getLowerMargin() * 2);
        domainAxis.setUpperMargin(domainAxis.getUpperMargin() * 2);
        if (dataset.getColumnCount() == 1)
            renderer.setItemMargin(renderer.getItemMargin() * 2);
        else
            domainAxis.setCategoryMargin(domainAxis.getCategoryMargin() * 2);

        /*System.out.println("2lowerMargin="+domainAxis.getLowerMargin());
        System.out.println("ItemMargin="+renderer.getItemMargin());
        System.out.println("CategoryMargin="+domainAxis.getCategoryMargin());*/

    }

    if (legendPanelOn)
        chart.removeLegend();
    return chart;

}

From source file:edu.ucla.stat.SOCR.chart.demo.CategoryStepChartDemo1.java

/**
 * Creates a chart.//  www . ja  va2 s  .  c  om
 * 
 * @param dataset  the dataset.
 * 
 * @return The chart.
 */
protected JFreeChart createChart(CategoryDataset dataset) {

    CategoryItemRenderer renderer = new CategoryStepRenderer(true);

    CategoryAxis domainAxis = new CategoryAxis(domainLabel);
    NumberAxis rangeAxis = new NumberAxis(rangeLabel);
    CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
    JFreeChart chart = new JFreeChart(chartTitle, plot);

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
    chart.setBackgroundPaint(Color.white);

    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.white);

    AbstractCategoryItemRenderer renderer2 = (AbstractCategoryItemRenderer) plot.getRenderer();
    renderer2.setLegendItemLabelGenerator(new SOCRCategorySeriesLabelGenerator());

    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    domainAxis.addCategoryLabelToolTip("Type 1", "The first type.");
    domainAxis.addCategoryLabelToolTip("Type 2", "The second type.");
    domainAxis.addCategoryLabelToolTip("Type 3", "The third type.");

    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setLabelAngle(0 * Math.PI / 2.0);
    // OPTIONAL CUSTOMISATION COMPLETED.

    setCategorySummary(dataset);
    if (legendPanelOn)
        chart.removeLegend();
    return chart;

}

From source file:org.jfree.chart.demo.CategoryStepChartDemo.java

/**
 * Creates a chart./*from  w w  w .  j a v  a  2  s .co m*/
 * 
 * @param dataset  the dataset.
 * 
 * @return The chart.
 */
private JFreeChart createChart(final CategoryDataset dataset) {

    final CategoryItemRenderer renderer = new CategoryStepRenderer(true);
    final CategoryAxis domainAxis = new CategoryAxis("Category");
    final ValueAxis rangeAxis = new NumberAxis("Value");
    final CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
    final JFreeChart chart = new JFreeChart("Category Step Chart", plot);

    // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...

    // set the background color for the chart...
    //        final StandardLegend legend = (StandardLegend) chart.getLegend();
    //      legend.setAnchor(StandardLegend.SOUTH);

    chart.setBackgroundPaint(Color.white);

    //        plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.white);

    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    domainAxis.addCategoryLabelToolTip("Type 1", "The first type.");
    domainAxis.addCategoryLabelToolTip("Type 2", "The second type.");
    domainAxis.addCategoryLabelToolTip("Type 3", "The third type.");

    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setLabelAngle(0 * Math.PI / 2.0);
    // OPTIONAL CUSTOMISATION COMPLETED.

    return chart;

}

From source file:edu.ucla.stat.SOCR.chart.ChartGenerator.java

private JFreeChart createBoxAndWhiskerChart(String title, String xLabel, String yLabel,
        BoxAndWhiskerCategoryDataset dataset) {

    CategoryAxis domainAxis = new CategoryAxis(xLabel);
    NumberAxis rangeAxis = new NumberAxis(yLabel);

    // CategoryItemRenderer renderer = new BoxAndWhiskerRenderer();
    BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
    CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer);
    JFreeChart chart = new JFreeChart(title, plot);

    chart.setBackgroundPaint(Color.white);

    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setDomainGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.white);

    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    //columnCount -- category count
    //RowCount -- serie count
    if (dataset.getColumnCount() * dataset.getRowCount() < 5) {

        domainAxis.setLowerMargin(0.2);/* w  ww  .j  a v  a 2  s. c om*/
        domainAxis.setUpperMargin(0.2);
        if (dataset.getColumnCount() == 1)
            renderer.setItemMargin(0.5);
        //   domainAxis.setCategoryMargin(domainAxis.getCategoryMargin()*2);

        /*   System.out.println("lowerMargin="+domainAxis.getLowerMargin());
           System.out.println("ItemMargin="+renderer.getItemMargin());
           System.out.println("CategoryMargin="+domainAxis.getCategoryMargin());*/
    }

    else if (dataset.getColumnCount() * dataset.getRowCount() < 10) {
        domainAxis.setLowerMargin(domainAxis.getLowerMargin() * 2);
        domainAxis.setUpperMargin(domainAxis.getUpperMargin() * 2);
        if (dataset.getColumnCount() == 1)
            renderer.setItemMargin(renderer.getItemMargin() * 2);
        else
            domainAxis.setCategoryMargin(domainAxis.getCategoryMargin() * 2);
        /*System.out.println("lowerMargin="+domainAxis.getLowerMargin());
         System.out.println("ItemMargin="+renderer.getItemMargin());
         System.out.println("CategoryMargin="+domainAxis.getCategoryMargin());
        */
    }

    return chart;
}