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:mekhq.gui.FinancesTab.java

private JFreeChart createMonthlyChart(CategoryDataset dataset) {
    JFreeChart chart = ChartFactory.createBarChart("", // title
            resourceMap.getString("graphDate.text"), // x-axis label
            resourceMap.getString("graphCBills.text"), // y-axis label
            dataset);/*from   w  ww . j av a2  s  .c  om*/

    chart.setBackgroundPaint(Color.WHITE);

    chart.getLegend().setPosition(RectangleEdge.TOP);

    return chart;
}

From source file:org.n52.oxf.render.sos.TimeSeriesChartRenderer4xPhenomenons.java

/**
 * The resulting IVisualization shows a chart which consists a TimeSeries for each FeatureOfInterest
 * contained in the observationCollection.
 *///www  .  j  a  v  a 2 s . c  om
public IVisualization renderChart(OXFFeatureCollection observationCollection, ParameterContainer paramCon,
        int width, int height) {
    JFreeChart chart = renderChart(observationCollection, paramCon);

    // draw plot into image:
    Plot plot = chart.getPlot();
    BufferedImage chartImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D chartGraphics = chartImage.createGraphics();
    chartGraphics.setColor(Color.white);
    chartGraphics.fillRect(0, 0, width, height);
    plot.draw(chartGraphics, new Rectangle2D.Float(0, 0, width, height), null, null, null);

    // draw legend into image:
    LegendTitle legend = chart.getLegend();
    BufferedImage legendImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D legendGraphics = legendImage.createGraphics();
    legendGraphics.setColor(Color.white);
    legendGraphics.fillRect(0, 0, (int) legend.getWidth(), (int) legend.getHeight());
    legend.draw(legendGraphics, new Rectangle2D.Float(0, 0, width, height));

    return new StaticVisualization(chartImage, legendImage);
}

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

protected void configureSubChart(final JFreeChart chart) {
    final TextTitle chartTitle = chart.getTitle();
    if (chartTitle != null) {
        if (getPieTitleFont() != null) {
            chartTitle.setFont(getPieTitleFont());
        } else {// w  w  w.  ja va2s  .c  o m
            final Font titleFont = Font.decode(getTitleFont());
            chartTitle.setFont(titleFont);
        }
    }

    if (isAntiAlias() == false) {
        chart.setAntiAlias(false);
    }

    final LegendTitle chLegend = chart.getLegend();
    if (chLegend != null) {
        final RectangleEdge loc = translateEdge(getLegendLocation().toLowerCase());
        if (loc != null) {
            chLegend.setPosition(loc);
        }
        if (getLegendFont() != null) {
            chLegend.setItemFont(Font.decode(getLegendFont()));
        }
        if (!isDrawLegendBorder()) {
            chLegend.setBorder(BlockBorder.NONE);
        }
        if (getLegendBackgroundColor() != null) {
            chLegend.setBackgroundPaint(getLegendBackgroundColor());
        }
        if (getLegendTextColor() != null) {
            chLegend.setItemPaint(getLegendTextColor());
        }
    }

    final Plot plot = chart.getPlot();
    plot.setNoDataMessageFont(Font.decode(getLabelFont()));

    final String pieNoData = getPieNoDataMessage();
    if (pieNoData != null) {
        plot.setNoDataMessage(pieNoData);
    } else {
        final String message = getNoDataMessage();
        if (message != null) {
            plot.setNoDataMessage(message);
        }
    }
}

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

/**
 * This is a helper method for creating a line chart. This should only do
 * the chart creation and not setting up the dataset. The calling method
 * should do the logic for the dataset setup.
 * @param c //  w ww . ja  v a2s.  c  om
 * 
 * @param xyCollection
 *            The dataset to display a chart for.
 * @param chartType
 *            The chart type. This must be a valid chart type that can be
 *            created from an XY dataset. At current only line and scatter
 *            are supported
 * @param legendPosition
 *            The position of the legend.
 * @param chartName
 *            The name of the chart.
 * @param yaxisName
 *            The name of the y axis.
 * @param xaxisName
 *            The name of the x axis.
 * @return A chart of the specified chartType based on the given dataset.
 */
private static JFreeChart createChartFromXYDataset(Chart c, XYDataset xyCollection, ChartType chartType,
        LegendPosition legendPosition, String chartName, String yaxisName, String xaxisName) {
    boolean showLegend = !legendPosition.equals(LegendPosition.NONE);
    JFreeChart chart;
    if (chartType.equals(ChartType.LINE)) {
        chart = ChartFactory.createXYLineChart(chartName, xaxisName, yaxisName, xyCollection,
                PlotOrientation.VERTICAL, showLegend, true, false);
    } else if (chartType.equals(ChartType.SCATTER)) {
        chart = ChartFactory.createScatterPlot(chartName, xaxisName, yaxisName, xyCollection,
                PlotOrientation.VERTICAL, showLegend, true, false);
    } else {
        throw new IllegalArgumentException("Unknown chart type " + chartType + " for an XY dataset.");
    }
    if (chart == null)
        return null;
    XYPlot plot = (XYPlot) chart.getPlot();

    // XXX the following instance check is brittle; there are many ways to represent a time
    // series in JFreeChart. This check uses knowledge of the inner workings of DatasetUtil.
    if (xyCollection instanceof TimePeriodValuesCollection) {
        logger.debug("Switching x-axis to date axis so labels render properly");
        plot.setDomainAxis(new DateAxis(xaxisName));
        // TODO user-settable date format
        // axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));
    }

    if (legendPosition != LegendPosition.NONE) {
        chart.getLegend().setPosition(legendPosition.getRectangleEdge());
    }

    if (!c.isAutoXAxisRange()) {
        XYPlot xyplot = chart.getXYPlot();
        ValueAxis axis = xyplot.getDomainAxis();
        axis.setAutoRange(false);
        axis.setRange(c.getXAxisMinRange(), c.getXAxisMaxRange());
    }
    if (!c.isAutoYAxisRange()) {
        XYPlot xyplot = chart.getXYPlot();
        ValueAxis axis = xyplot.getRangeAxis();
        axis.setAutoRange(false);
        axis.setRange(c.getYAxisMinRange(), c.getYAxisMaxRange());
    }

    return chart;
}

From source file:Applet.EmbeddedChart.java

/**
 * Creates a chart.//from   ww w.j a  va2  s  .com
 * 
 * @param dataset
 *            the data for the chart.
 * 
 * @return a chart.
 */
private JFreeChart createChart(final XYDataset dataset, String title, boolean gofr) {

    // create the chart...
    final JFreeChart chart = ChartFactory.createXYLineChart(null, // chart
            // title
            "Radial Distance,  r/\u03c3", // x axis label
            title, // y axis label
            dataset, // data
            PlotOrientation.VERTICAL, true, // include legend
            true, // tooltips
            false // urls
    );

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

    // final StandardLegend legend = (StandardLegend) chart.getLegend();
    // legend.setDisplaySeriesShapes(true);

    // get a reference to the plot for further customisation...
    final XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.lightGray);
    // plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    XYTitleAnnotation xyta = new XYTitleAnnotation(0.98, 0.98, chart.getLegend(), RectangleAnchor.TOP_RIGHT);
    chart.removeLegend();
    plot.addAnnotation(xyta);

    final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);

    for (int i = 0; i < 2; i++) {
        renderer.setSeriesPaint(i * 6 + 0, new Color(255, 0, 0));
        renderer.setSeriesPaint(i * 6 + 1, new Color(0, 0, 255));
        renderer.setSeriesPaint(i * 6 + 2, new Color(0, 139, 0));
        renderer.setSeriesPaint(i * 6 + 3, new Color(255, 165, 0));
        renderer.setSeriesPaint(i * 6 + 4, new Color(255, 0, 255));
        renderer.setSeriesPaint(i * 6 + 5, new Color(0, 0, 0));

        renderer.setSeriesStroke(i * 6 + 0, new BasicStroke(1.3f, BasicStroke.CAP_SQUARE,
                BasicStroke.JOIN_MITER, 10.0f, new float[] { 10.0f }, 0.0f));
        renderer.setSeriesStroke(i * 6 + 1, new BasicStroke(1.3f, BasicStroke.CAP_SQUARE,
                BasicStroke.JOIN_MITER, 10.0f, new float[] { 50.0f, 2.0f }, 0.0f));
        renderer.setSeriesStroke(i * 6 + 2, new BasicStroke(1.3f, BasicStroke.JOIN_ROUND,
                BasicStroke.JOIN_MITER, 10.0f, new float[] { 30.0f, 1.0f, 1.0f }, 0.0f));
        renderer.setSeriesStroke(i * 6 + 3, new BasicStroke(1.3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
                10.0f, new float[] { 1.0f, 3.0f }, 0.0f));
        renderer.setSeriesStroke(i * 6 + 4, new BasicStroke(1.3f, BasicStroke.CAP_SQUARE,
                BasicStroke.JOIN_MITER, 10.0f, new float[] { 1.0f, 2.0f, 3.0f, 4.0f }, 0.0f));
        renderer.setSeriesStroke(i * 6 + 5, new BasicStroke(1.3f, BasicStroke.CAP_SQUARE,
                BasicStroke.JOIN_MITER, 10.0f, new float[] { 5.0f, 1.0f, 20.0f, 1.0f }, 0.0f));
    }

    plot.setRenderer(renderer);

    return chart;

}

From source file:gavisualizer.LineChart.java

@Override
public void generate() {
    // Creates Line Chart from variables
    JFreeChart chart = ChartFactory.createLineChart(_title, // chart title
            _axisLabelDomain, // domain axis label
            _axisLabelRange, // range axis label
            _dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            false, // tooltips
            false // urls
    );//from  w w w.j av a  2 s.  c o m

    // Set the Plot to certain colors
    final CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setOutlinePaint(Color.white);

    // Set Legend to the right of the chart
    final LegendTitle lt = (LegendTitle) chart.getLegend();
    lt.setPosition(RectangleEdge.RIGHT);

    // Set paints for lines in the chart
    LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
    DefaultDrawingSupplier dw = new DefaultDrawingSupplier(PAINTS,
            DefaultDrawingSupplier.DEFAULT_OUTLINE_PAINT_SEQUENCE,
            DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
            DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
            DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
    plot.setDrawingSupplier(dw);

    // Customize stroke width of the series
    ((AbstractRenderer) renderer).setAutoPopulateSeriesStroke(false);
    renderer.setBaseStroke(STROKE_WIDTH);
    renderer.setBaseShapesVisible(false);

    // Include dashed lines if necessary
    List<String> rows = _dataset.getRowKeys();

    // See if the title includes Downloads (Dashed lines are for Download lines)
    if (rows.get(rows.size() - 1).endsWith("Downloads")) {
        // Set the start to half the rows
        int start = _dataset.getRowCount() / 2;

        // Create an initial value
        int init = 0;

        // Iterate through the Download lines
        while (start < _dataset.getRowCount()) {
            // Make sure series and legend have dashes
            renderer.setSeriesStroke(start, DASHED_STROKE);
            LegendItemCollection legend = renderer.getLegendItems();
            LegendItem li = legend.get(start - 1);
            li.setLineStroke(DASHED_STROKE);

            // Make sure the color matches the undashed year
            renderer.setSeriesPaint(start, renderer.getItemPaint(init, 0));
            init++;
            start++;
        }
    }

    // Customise the range axis...
    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setAutoRangeIncludesZero(true);

    _chart = chart;
}

From source file:com.rapidminer.gui.plotter.DistributionPlotter.java

public void paintComponent(Graphics graphics, int width, int height) {
    preparePlots();//w ww.  j a v  a2  s .co  m
    if (plot) {
        JFreeChart chart = null;
        try {
            if (!Double.isNaN(model.getUpperBound(plotColumn))) {
                chart = createNumericalChart();
            } else {
                chart = createNominalChart();
            }
        } catch (Exception e) {
            // do nothing - just do not draw the chart
        }

        if (chart != null) {
            // 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, width, height);
            chart.draw((Graphics2D) graphics, drawRect);
        }
    }
}

From source file:net.praqma.jenkins.memorymap.MemoryMapBuildAction.java

protected JFreeChart createChart(CategoryDataset dataset, String title, String yaxis, int max, int min) {
    final JFreeChart chart = ChartFactory.createStackedAreaChart(title, // chart                                                                                                                                       // title
            null, // unused
            yaxis, // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );//from   w  ww.  j a va  2 s .co m

    final LegendTitle legend = chart.getLegend();

    legend.setPosition(RectangleEdge.BOTTOM);

    chart.setBackgroundPaint(Color.white);

    final CategoryPlot plot = chart.getCategoryPlot();

    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.setUpperBound(max);
    rangeAxis.setLowerBound(min);

    final StackedAreaRenderer renderer = (StackedAreaRenderer) plot.getRenderer();
    renderer.setBaseStroke(new BasicStroke(2.0f));
    plot.setInsets(new RectangleInsets(5.0, 0, 0, 5.0));
    return chart;
}

From source file:com.mxgraph.examples.swing.chart.TimeSeriesChartDemo1.java

/**
 * Creates a chart./*from   www.j  a v a 2s  .  co m*/
 *
 * @param dataset  a dataset.
 *
 * @return A chart.
 */
public static JFreeChart createChart(XYDataset dataset, String name) {

    JFreeChart chart = ChartFactory.createTimeSeriesChart(name, // title
            "Date", // x-axis label
            "Value", // y-axis label
            dataset, // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );

    chart.setBackgroundPaint(Color.white);

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    XYItemRenderer r = plot.getRenderer();
    if (r instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
        renderer.setBaseShapesVisible(true);
        renderer.setBaseShapesFilled(true);
        renderer.setDrawSeriesLineAsPath(true);
        renderer.setItemLabelGenerator(new StandardXYItemLabelGenerator());
        renderer.setBaseItemLabelsVisible(true);
        // 
        renderer.setItemLabelsVisible(true);
        // 
        renderer.setBaseShapesVisible(true);
        // 
        renderer.setBaseShapesFilled(true);

        //  renderer.setLegendItemLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})"));

    }

    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss"/*"yyyy-MM-dd HH:mm:ss"*/));

    chart.getTitle().setFont(new Font("", Font.BOLD, 15));
    chart.getLegend().setItemFont(new Font("", Font.BOLD, 15));
    //
    plot.getRangeAxis().setLabelFont(new Font("", Font.BOLD, 15));
    //
    chart.getLegend().setItemFont(new Font("", Font.ITALIC, 15));
    //
    plot.getDomainAxis().setTickLabelFont(new Font("", 1, 15));
    //
    plot.getDomainAxis().setLabelFont(new Font("", 1, 12));

    return chart;

}

From source file:jmemorize.gui.swing.panels.DeckChartPanel.java

private JFreeChart createChart() {
    m_dataset = createDefaultDataSet();//www .ja va 2 s .  co  m

    JFreeChart chart = ChartFactory.createStackedBarChart3D(null, // chart title
            null, // domain axis label
            Localization.get("DeckChart.CARDS"), // range axis label //$NON-NLS-1$
            m_dataset, // data
            PlotOrientation.VERTICAL, // the plot orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    // setup legend
    // TODO we used to do this for the old jfreechar version, but it's not clear why.
    // can we get rid of it?
    LegendTitle legend = chart.getLegend();
    //        legend.setsetRenderingOrder(LegendRenderingOrder.REVERSE);
    legend.setItemFont(legend.getItemFont().deriveFont(11f));

    // setup plot
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    TickUnitSource tickUnits = NumberAxis.createIntegerTickUnits();
    plot.getRangeAxis().setStandardTickUnits(tickUnits); //CHECK use locale
    plot.setForegroundAlpha(0.99f);

    // setup renderer
    m_barRenderer = new MyBarRenderer();
    m_barRenderer.setItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    m_barRenderer.setItemLabelsVisible(true);
    m_barRenderer
            .setPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER));
    plot.setRenderer(m_barRenderer);
    setSeriesPaint();

    return chart;
}