Example usage for org.jfree.chart JFreeChart getLegend

List of usage examples for org.jfree.chart JFreeChart getLegend

Introduction

In this page you can find the example usage for org.jfree.chart JFreeChart getLegend.

Prototype

public LegendTitle getLegend() 

Source Link

Document

Returns the legend for the chart, if there is one.

Usage

From source file:ca.sqlpower.wabit.swingui.chart.ChartSwingUtil.java

/**
 * This is a helper method for creating charts and is split off as it does
 * only the chart creation and tweaking of a category chart. All of the
 * decisions for what columns are defined as what and how the data is stored
 * should be done in the method that calls this.
 * <p>//from w ww  .j  a  v a 2 s.  co m
 * Given a dataset and other chart properties this will create an
 * appropriate JFreeChart.
 * @param c 
 * 
 * @param dataset
 *            The data to create a chart from.
 * @param chartType
 *            The type of chart to create for the category dataset.
 * @param legendPosition
 *            The position where the legend should appear.
 * @param chartName
 *            The title of the chart.
 * @param yaxisName
 *            The title of the Y axis.
 * @param xaxisName
 *            The title of the X axis.
 * @return A JFreeChart that represents the dataset given.
 */
private static JFreeChart createCategoryChartFromDataset(Chart c, CategoryDataset dataset, ChartType chartType,
        LegendPosition legendPosition, String chartName, String yaxisName, String xaxisName) {

    if (chartType == null || dataset == null) {
        return null;
    }
    boolean showLegend = !legendPosition.equals(LegendPosition.NONE);

    JFreeChart chart;
    ChartFactory.setChartTheme(StandardChartTheme.createLegacyTheme());
    BarRenderer.setDefaultBarPainter(new StandardBarPainter());

    if (chartType == ChartType.BAR) {
        chart = ChartFactory.createBarChart(chartName, xaxisName, yaxisName, dataset, PlotOrientation.VERTICAL,
                showLegend, true, false);

    } else if (chartType == ChartType.PIE) {
        chart = createPieChart(chartName, dataset, TableOrder.BY_ROW, showLegend, true, false);

    } else if (chartType == ChartType.CATEGORY_LINE) {
        chart = ChartFactory.createLineChart(chartName, xaxisName, yaxisName, dataset, PlotOrientation.VERTICAL,
                showLegend, true, false);
    } else {
        throw new IllegalArgumentException("Unknown chart type " + chartType + " for a category dataset.");
    }
    if (chart == null)
        return null;

    if (legendPosition != LegendPosition.NONE) {
        chart.getLegend().setPosition(legendPosition.getRectangleEdge());
        //chart.getTitle().setPadding(4,4,15,4);
    }

    if (chart.getPlot() instanceof MultiplePiePlot) {
        MultiplePiePlot mplot = (MultiplePiePlot) chart.getPlot();
        PiePlot plot = (PiePlot) mplot.getPieChart().getPlot();
        plot.setLabelLinkStyle(PieLabelLinkStyle.CUBIC_CURVE);
        if (showLegend) {
            // for now, legend and items labels are mutually exclusive. Could make this a user pref.
            plot.setLabelGenerator(null);
        }
    }

    if (!c.isAutoYAxisRange()) {
        CategoryPlot plot = chart.getCategoryPlot();
        ValueAxis axis = plot.getRangeAxis();
        axis.setAutoRange(false);
        axis.setRange(c.getYAxisMinRange(), c.getYAxisMaxRange());
    }

    return chart;
}

From source file:uom.research.thalassemia.util.BarChartCreator.java

/**
 * Creates a sample chart.//from www .ja v  a  2s .  c o m
 *
 * @param dataset the dataset.
 *
 * @return The chart.
 */
private JFreeChart createChart(final CategoryDataset dataset) {
    JFreeChart chart = ChartFactory.createBarChart(mainTitle, xTitle, yTitle, dataset);
    chart.addSubtitle(new TextTitle(subTitle));
    chart.setBackgroundPaint(Color.white);
    CategoryPlot plot = (CategoryPlot) chart.getPlot();

    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);
    chart.getLegend().setFrame(BlockBorder.NONE);
    return chart;
}

From source file:org.gumtree.vis.awt.PlotFactory.java

public static JFreeChart createXYErrorChart(IXYErrorDataset dataset) {

    JFreeChart chart;
    String title = null;//from   w  ww  .  j  a  v a2 s.c  o  m
    String xTitle = null;
    String yTitle = null;
    if (dataset != null) {
        title = "";
        if (dataset.getTitle() != null) {
            title = dataset.getTitle();
        }
        xTitle = "";
        if (dataset.getXTitle() != null) {
            xTitle += dataset.getXTitle();
        }
        if (dataset.getXUnits() != null) {
            xTitle += " (" + dataset.getXUnits() + ")";
        }
        yTitle = "";
        if (dataset.getYTitle() != null) {
            yTitle += dataset.getYTitle();
        }
        if (dataset.getYUnits() != null) {
            yTitle += " (" + dataset.getYUnits() + ")";
        }
    } else {
        dataset = new XYErrorDataset();
    }
    chart = createXYLineChart(title, xTitle, yTitle, dataset, PlotOrientation.VERTICAL, true, false, true);
    chart.setBackgroundPaint(Color.WHITE);
    final LegendTitle legend = (LegendTitle) chart.getLegend();
    RectangleEdge legendPosition = RectangleEdge.BOTTOM;
    try {
        String legendProperty = "RectangleEdge." + System.getProperty("kuranda1D.legendPosition");
        if (RectangleEdge.BOTTOM.toString().equals(legendProperty))
            legendPosition = RectangleEdge.BOTTOM;
        else if (RectangleEdge.RIGHT.toString().equals(legendProperty))
            legendPosition = RectangleEdge.RIGHT;
        else if (RectangleEdge.LEFT.toString().equals(legendProperty))
            legendPosition = RectangleEdge.LEFT;
        else if (RectangleEdge.TOP.toString().equals(legendProperty))
            legendPosition = RectangleEdge.TOP;
    } catch (Exception e) {
        // TODO: handle exception
    }
    legend.setPosition(legendPosition);
    chart.setBorderVisible(true);
    //      ChartUtilities.applyCurrentTheme(chart);
    //      chartTheme.apply(chart);

    XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    //      plot.setRangeZeroBaselineVisible(false);
    //      plot.setDomainZeroBaselineVisible(false);
    ValueAxis rangeAxis = plot.getRangeAxis();
    if (rangeAxis instanceof NumberAxis) {
        ((NumberAxis) rangeAxis).setAutoRangeStickyZero(false);
        ((NumberAxis) rangeAxis).setAutoRangeIncludesZero(false);
    }
    ValueAxis domainAxis = plot.getDomainAxis();
    if (domainAxis instanceof NumberAxis) {
        ((NumberAxis) domainAxis).setAutoRangeStickyZero(false);
        ((NumberAxis) domainAxis).setAutoRangeIncludesZero(false);
    }
    plot.setDomainPannable(true);
    plot.setRangePannable(true);

    plot.setDomainGridlinesVisible(true);
    //        plot.setDomainCrosshairLockedOnData(true);
    //        plot.setDomainCrosshairVisible(true);
    plot.setRangeGridlinesVisible(true);
    //        plot.setRangeCrosshairLockedOnData(true);
    //        plot.setRangeCrosshairVisible(true);

    //      xAxis = plot.getDomainAxis();
    //        yAxis = plot.getRangeAxis();

    plot.setDataset(dataset);
    XYItemRenderer renderer = chart.getXYPlot().getRenderer();
    if (renderer instanceof XYErrorRenderer) {
        //         ((XYLineAndShapeRenderer) renderer).setBaseShapesVisible(true);
        ((XYErrorRenderer) renderer).setBaseShapesFilled(true);
        ((XYErrorRenderer) renderer).setDrawXError(false);
        ((XYErrorRenderer) renderer).setDrawYError(true);
    }

    chart.fireChartChanged();
    return chart;
}

From source file:com.thalesgroup.hudson.plugins.klocwork.graph.KloTrendGraph.java

@Override
protected JFreeChart createGraph() {
    final JFreeChart chart = ChartFactory.createLineChart(null, // chart title
            null, // unused
            yLabel, // range axis label
            categoryDataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );/*from   w w w.  j ava  2 s  .c  om*/

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

    final LegendTitle legend = chart.getLegend();
    legend.setPosition(RectangleEdge.RIGHT);

    chart.setBackgroundPaint(Color.white);

    final CategoryPlot plot = chart.getCategoryPlot();

    // plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
    plot.setBackgroundPaint(Color.WHITE);
    plot.setOutlinePaint(null);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.black);

    CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
    plot.setDomainAxis(domainAxis);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    domainAxis.setCategoryMargin(0.0);

    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setLowerBound(0);
    rangeAxis.setAutoRange(true);

    final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
    renderer.setBaseStroke(new BasicStroke(2.0f));
    ColorPalette.apply(renderer);

    // crop extra space around the graph
    plot.setInsets(new RectangleInsets(5.0, 0, 0, 5.0));

    return chart;
}

From source file:org.jenkinsci.plugins.autozoil.graph.AutozoilGraph.java

/**
 * Creates a Autozoil trend graph//ww  w. j a va2s.  c  o m
 *
 * @return the JFreeChart graph object
 */
protected JFreeChart createGraph() {

    final JFreeChart chart = ChartFactory.createLineChart(null, // chart title
            null, // unused
            yLabel, // range axis label
            categoryDataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

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

    final LegendTitle legend = chart.getLegend();
    legend.setPosition(RectangleEdge.RIGHT);

    chart.setBackgroundPaint(Color.white);

    final CategoryPlot plot = chart.getCategoryPlot();

    // plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
    plot.setBackgroundPaint(Color.WHITE);
    plot.setOutlinePaint(null);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.black);

    CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
    plot.setDomainAxis(domainAxis);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    domainAxis.setCategoryMargin(0.0);

    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setLowerBound(0);
    rangeAxis.setAutoRange(true);

    final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
    renderer.setBaseStroke(new BasicStroke(2.0f));
    ColorPalette.apply(renderer);

    // crop extra space around the graph
    plot.setInsets(new RectangleInsets(5.0, 0, 0, 5.0));

    return chart;
}

From source file:uk.ac.lkl.cram.ui.chart.AbstractChartMaker.java

/**
 * Apply some defaults to a chart, including background paint
 * and font./*from   w  w  w . j  a  v  a2 s  .  c  o m*/
 * @param chart the chart to which defaults should be applied
 */
private void setChartDefaults(JFreeChart chart) {
    Paint backgroundPaint = UIManager.getColor("InternalFrame.background");
    //Set the background colour of the chart
    chart.setBackgroundPaint(backgroundPaint);
    //Set the background colour of the plot to be the same as the chart
    Plot plot = chart.getPlot();
    plot.setBackgroundPaint(backgroundPaint);
    //No outline around the bars
    plot.setOutlineVisible(false);
    //Get the legend
    LegendTitle legend = chart.getLegend();
    //Set the font of the legend to be the same as the platform
    legend.setItemFont(UIManager.getFont("Label.font"));
    //Set the background colour of the legend to be the same as the platform
    legend.setBackgroundPaint(backgroundPaint);
    //No frame around the legend
    legend.setFrame(BlockBorder.NONE);
    //Locate the legend to the right of the chart
    legend.setPosition(RectangleEdge.RIGHT);
}

From source file:uk.ac.ed.epcc.webapp.charts.jfreechart.JFreePieChartData.java

@Override
public JFreeChart getJFreeChart() {
    DefaultPieDataset pieDataset = makeDataSet();

    JFreeChart chart = ChartFactory.createPieChart(title, // Title
            pieDataset, // Dataset
            true // Show legend
            , false, false);//from w  w  w  .  j  a v  a 2  s. co  m
    PiePlot plot = (PiePlot) chart.getPlot();

    StandardPieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator("{0} ({2})");

    plot.setLabelGenerator(gen);
    plot.setMaximumLabelWidth(0.07);
    plot.setLabelFont(plot.getLabelFont().deriveFont(9.0F));

    LegendTitle leg = chart.getLegend();

    leg.setPosition(RectangleEdge.RIGHT);
    if (!colours.isEmpty()) {
        String legends[] = ds.getLegends();

        for (int i = 0; i < ds.getNumSets(); i++) {
            if (legends != null && legends.length > i && colours.size() > i) {
                Color c = colours.get(i);
                plot.setSectionPaint(legends[i], c);
            }
        }
    }

    return chart;

}

From source file:com.rapidminer.gui.plotter.charts.AbstractBarChartPlotter.java

public void paintBarChart(Graphics graphics) {
    int categoryCount = prepareData();
    String groupByName = groupByColumn >= 0 ? dataTable.getColumnName(groupByColumn) : null;
    String valueName = valueColumn >= 0 ? dataTable.getColumnName(valueColumn) : null;
    String maxClassesProperty = System.getProperty(MainFrame.PROPERTY_RAPIDMINER_GUI_PLOTTER_COLORS_CLASSLIMIT);
    int maxClasses = 20;
    try {/*from  w  ww.j  ava 2  s . c  o  m*/
        if (maxClassesProperty != null)
            maxClasses = Integer.parseInt(maxClassesProperty);
    } catch (NumberFormatException e) {
        LogService.getGlobal().log(
                "Bar Chart plotter: cannot parse property 'rapidminer.gui.plotter.colors.classlimit', using maximal 20 different classes.",
                LogService.WARNING);
    }
    boolean createLegend = categoryCount > 0 && categoryCount < maxClasses;

    if (categoryCount <= MAX_CATEGORIES) {
        JFreeChart chart = createChart(categoryDataSet, groupByName, valueName, createLegend);

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

        // legend settings
        LegendTitle legend = chart.getLegend();
        if (legend != null) {
            legend.setPosition(RectangleEdge.TOP);
            legend.setFrame(BlockBorder.NONE);
            legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
        }

        Rectangle2D drawRect = new Rectangle2D.Double(0, 0, getWidth(), getHeight());
        chart.draw((Graphics2D) graphics, drawRect);
    } else {
        graphics.drawString("Too many columns (" + categoryCount + "), this chart is only able to plot up to "
                + MAX_CATEGORIES + " different categories", MARGIN, MARGIN);
    }
}

From source file:org.talend.dataprofiler.chart.util.TopChartFactory.java

private static void decorateCategoryPlot(JFreeChart chart) {

    XYPlot plot = chart.getXYPlot();//from w  ww . ja  v  a  2s .  com
    XYItemRenderer render = plot.getRenderer();
    ValueAxis domainAxis = plot.getDomainAxis();
    ValueAxis valueAxis = plot.getRangeAxis();

    Font font = new Font("Tahoma", Font.BOLD, BASE_ITEM_LABEL_SIZE); //$NON-NLS-1$

    render.setBaseItemLabelFont(font);
    font = new Font("sans-serif", Font.BOLD, BASE_LABEL_SIZE); //$NON-NLS-1$
    domainAxis.setLabelFont(font);
    font = new Font("sans-serif", Font.BOLD, BASE_LABEL_SIZE); //$NON-NLS-1$
    valueAxis.setLabelFont(font);
    font = new Font("sans-serif", Font.PLAIN, BASE_TICK_LABEL_SIZE); //$NON-NLS-1$
    domainAxis.setTickLabelFont(font);
    valueAxis.setTickLabelFont(font);
    font = new Font("Tahoma", Font.PLAIN, BASE_LEGEND_LABEL_SIZE); //$NON-NLS-1$
    LegendTitle legend = chart.getLegend();
    if (legend != null) {
        legend.setItemFont(font);
    }
    font = new Font("sans-serif", Font.BOLD, BASE_TITLE_LABEL_SIZE); //$NON-NLS-1$
    TextTitle title = chart.getTitle();
    if (title != null) {
        title.setFont(font);
    }
    font = null;
    if (render instanceof BarRenderer) {
        int rowCount = chart.getCategoryPlot().getDataset().getRowCount();
        domainAxis.setUpperMargin(0.1);
        // domainAxis.setMaximumCategoryLabelLines(10);
        ((BarRenderer) render).setItemMargin(-0.40 * rowCount);
    }
    // set color
    int rowCount = chart.getXYPlot().getDataset().getSeriesCount();
    for (int i = 0; i < rowCount; i++) {
        plot.getRenderer().setSeriesPaint(i, Color.RED);
    }

}

From source file:com.thalesgroup.hudson.plugins.cppcheck.graph.CppcheckGraph.java

/**
 * Creates a Cppcheck trend graph//from   w  w w  . j a v  a2  s .  c o m
 *
 * @return the JFreeChart graph object
 */
protected JFreeChart createGraph() {

    final JFreeChart chart = ChartFactory.createLineChart(null, // chart title
            null, // unused
            yLabel, // range axis label
            categoryDataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

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

    final LegendTitle legend = chart.getLegend();
    legend.setPosition(RectangleEdge.RIGHT);

    chart.setBackgroundPaint(Color.white);

    final CategoryPlot plot = chart.getCategoryPlot();

    // plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
    plot.setBackgroundPaint(Color.WHITE);
    plot.setOutlinePaint(null);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.black);

    CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
    plot.setDomainAxis(domainAxis);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
    domainAxis.setLowerMargin(0.0);
    domainAxis.setUpperMargin(0.0);
    domainAxis.setCategoryMargin(0.0);

    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setLowerBound(0);
    rangeAxis.setAutoRange(true);

    final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
    renderer.setBaseStroke(new BasicStroke(2.0f));
    applyColorPalette(renderer);

    // crop extra space around the graph
    plot.setInsets(new RectangleInsets(5.0, 0, 0, 5.0));

    return chart;
}