Example usage for org.jfree.chart.title LegendTitle LegendTitle

List of usage examples for org.jfree.chart.title LegendTitle LegendTitle

Introduction

In this page you can find the example usage for org.jfree.chart.title LegendTitle LegendTitle.

Prototype

public LegendTitle(LegendItemSource source) 

Source Link

Document

Constructs a new (empty) legend for the specified source.

Usage

From source file:ecosim.gui.SummaryPane.java

/**
 *  Private method to build the binning chart.
 *
 *  @return A ChartPanel containing the binning chart.
 *//*  w w  w  .  j  ava  2s.c om*/
private ChartPanel makeBinningChart() {
    final DefaultXYDataset binData = new DefaultXYDataset();
    final NumberFormat nf = NumberFormat.getInstance();
    final NumberAxis xAxis = new NumberAxis("Sequence identity criterion");
    nf.setMinimumFractionDigits(2);
    xAxis.setLowerBound(Binning.binLevels[0]);
    xAxis.setUpperBound(1.0D);
    xAxis.setTickUnit(new NumberTickUnit(0.05D, nf));
    LogAxis yAxis = new LogAxis("Number of bins");
    yAxis.setBase(2.0D);
    yAxis.setNumberFormatOverride(NumberFormat.getInstance());
    yAxis.setTickUnit(new NumberTickUnit(2.0D));
    yAxis.setMinorTickMarksVisible(true);
    yAxis.setAutoRangeMinimumSize(4.0D);
    yAxis.setSmallestValue(1.0D);
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
    for (int i = 0; i < seriesColors.length; i++) {
        renderer.setSeriesPaint(i, seriesColors[i]);
        renderer.setSeriesStroke(i, new BasicStroke(seriesStroke[i]));
    }
    XYPlot plot = new XYPlot(binData, xAxis, yAxis, renderer);
    JFreeChart binChart = new JFreeChart(null, JFreeChart.DEFAULT_TITLE_FONT, plot, false);
    binChart.setPadding(new RectangleInsets(0.0D, 0.0D, 0.0D, 10.0D));
    LegendTitle legend = new LegendTitle(plot);
    legend.setMargin(new RectangleInsets(1.0D, 1.0D, 1.0D, 1.0D));
    legend.setFrame(new LineBorder());
    legend.setBackgroundPaint(Color.white);
    legend.setPosition(RectangleEdge.BOTTOM);
    plot.addAnnotation(new XYTitleAnnotation(0.001D, 0.999D, legend, RectangleAnchor.TOP_LEFT));
    final ChartPanel pane = new ChartPanel(binChart, false, true, true, false, false);
    // Watch for changes to the Summary object.
    summary.addObserver(new Observer() {
        public void update(Observable o, Object obj) {
            Summary s = (Summary) obj;
            ParameterEstimate estimate = s.getEstimate();
            ArrayList<BinLevel> bins = s.getBins();
            if (bins.size() > 0) {
                double[][] values = new double[2][bins.size()];
                Double low = 1.0d;
                for (int i = 0; i < bins.size(); i++) {
                    BinLevel bin = bins.get(i);
                    values[0][i] = bin.getCrit();
                    values[1][i] = bin.getLevel();
                    if (values[0][i] < low)
                        low = values[0][i];
                }
                binData.addSeries("sequences", values);
                xAxis.setLowerBound(low);
                if (low > 0.95d - MasterVariables.EPSILON) {
                    xAxis.setTickUnit(new NumberTickUnit(0.005D, nf));
                } else if (low > 0.90d - MasterVariables.EPSILON) {
                    xAxis.setTickUnit(new NumberTickUnit(0.010D, nf));
                } else if (low > 0.80d - MasterVariables.EPSILON) {
                    xAxis.setTickUnit(new NumberTickUnit(0.025D, nf));
                }
                if (estimate != null) {
                    double[][] omega = new double[2][bins.size()];
                    double[][] sigma = new double[2][bins.size()];
                    double[] omegaLine = estimate.getOmega();
                    double[] sigmaLine = estimate.getSigma();
                    for (int i = 0; i < bins.size(); i++) {
                        double crit = 1.0D - values[0][i];
                        double snp = s.getLength() * crit;
                        omega[0][i] = values[0][i];
                        sigma[0][i] = values[0][i];
                        omega[1][i] = Math.pow(2.0D, snp * omegaLine[0] + omegaLine[1]);
                        sigma[1][i] = Math.pow(2.0D, snp * sigmaLine[0] + sigmaLine[1]);
                    }
                    if (-1.0D * omegaLine[0] > MasterVariables.EPSILON) {
                        binData.addSeries("omega", omega);
                    }
                    if (-1.0D * sigmaLine[0] > MasterVariables.EPSILON) {
                        binData.addSeries("sigma", sigma);
                    }
                }
                // Repaint the summary pane.
                pane.repaint();
            }
        }
    });
    return pane;
}

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

@SuppressWarnings("unchecked")
@Override// w w w .j  a v  a  2 s. co m
public void initialize() throws GraphException {
    String title = getParam(GraphSource.GRAPH_TITLE, String.class, DEFAULT_TITLE);
    boolean legend = getParam(GraphSource.GRAPH_LEGEND, Boolean.class, DEFAULT_GRAPH_LEGEND);
    boolean graphToolTip = getParam(GraphSource.GRAPH_TOOL_TIP, Boolean.class, DEFAULT_GRAPH_TOOL_TIP);
    boolean graphDisplayLabel = getParam(GraphSource.GRAPH_DISPLAY_LABEL, Boolean.class, false);
    boolean legendBorder = getParam(GraphSource.LEGEND_BORDER, Boolean.class, DEFAULT_LEGEND_BORDER);
    boolean graphBorder = getParam(GraphSource.GRAPH_BORDER, Boolean.class, DEFAULT_GRAPH_BORDER);
    Font titleFont = getParam(GraphSource.GRAPH_FONT, Font.class, DEFAULT_GRAPH_TITLE_FONT);
    String noDataMessage = getParam(GraphSource.GRAPH_NO_DATA_MESSAGE, String.class,
            DEFAULT_GRAPH_NO_DATA_MESSAGE);
    PieGraphData pieGraphData = makeDataSet();
    Map<Comparable, Paint> colors = pieGraphData.colors;

    this.chart = ChartFactory.createPieChart(title, pieGraphData.data, false, graphToolTip, false);

    Paint backgroundColor = getParam(GraphSource.BACKGROUND_COLOR, Paint.class, DEFAULT_BACKGROUND_COLOR);
    Paint plotColor = getParam(JFreeChartTimeSeriesGraphSource.PLOT_COLOR, Paint.class, backgroundColor);
    Paint labelColor = getParam(JFreeChartTimeSeriesGraphSource.GRAPH_LABEL_BACKGROUND_COLOR, Paint.class,
            DEFAULT_BACKGROUND_COLOR);

    this.chart.setBackgroundPaint(backgroundColor);
    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(plotColor);
    plot.setNoDataMessage(noDataMessage);

    if (!graphDisplayLabel) {
        plot.setLabelGenerator(null);
    } else {
        plot.setInteriorGap(0.001);
        plot.setMaximumLabelWidth(.3);
        //           plot.setIgnoreNullValues(true);
        plot.setIgnoreZeroValues(true);
        plot.setShadowPaint(null);
        //           plot.setOutlineVisible(false);
        //TODO use title font?
        Font font = plot.getLabelFont();
        plot.setLabelLinkStyle(PieLabelLinkStyle.CUBIC_CURVE);
        plot.setLabelFont(font.deriveFont(font.getSize2D() * .75f));
        plot.setLabelBackgroundPaint(labelColor);
        plot.setLabelShadowPaint(null);
        plot.setLabelOutlinePaint(null);
        plot.setLabelGap(0.001);
        plot.setLabelLinkMargin(0.0);
        plot.setLabelLinksVisible(true);
        //           plot.setSimpleLabels(true);
        //           plot.setCircular(true);
    }

    if (!graphBorder) {
        plot.setOutlineVisible(false);
    }

    if (title != null && !"".equals(title)) {
        TextTitle title1 = new TextTitle();
        title1.setText(title);
        title1.setFont(titleFont);
        title1.setPadding(3, 2, 5, 2);
        chart.setTitle(title1);
    } else {
        chart.setTitle((TextTitle) null);
    }
    plot.setLabelPadding(new RectangleInsets(1, 1, 1, 1));
    //Makes a wrapper for the legend to remove the border around it
    if (legend) {
        LegendTitle legend1 = 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 = legend1.getItemContainer();
        items.setPadding(2, 10, 5, 2);
        wrapper.add(items);
        legend1.setWrapper(wrapper);
        legend1.setPosition(RectangleEdge.BOTTOM);
        legend1.setHorizontalAlignment(HorizontalAlignment.CENTER);

        if (params.get(GraphSource.LEGEND_FONT) instanceof Font) {
            legend1.setItemFont(((Font) params.get(GraphSource.LEGEND_FONT)));
        }

        chart.addSubtitle(legend1);
        plot.setLegendLabelGenerator(new PieGraphLabelGenerator());
    }

    for (Comparable category : colors.keySet()) {
        plot.setSectionPaint(category, colors.get(category));
    }

    plot.setToolTipGenerator(new PieGraphToolTipGenerator(pieGraphData));
    plot.setURLGenerator(new PieGraphURLGenerator(pieGraphData));

    initialized = true;
}

From source file:org.squale.squaleweb.util.graph.KiviatMaker.java

/**
 * Create the JreeChart object/* w  ww .j  a  v  a 2s .  co  m*/
 * 
 * @param showLegend indicate if it should display the legend or not
 * @param showBackground indicate if we want showBackground
 * @return The JreeChart object
 */
public JFreeChart getChart(boolean showLegend, boolean showBackground) {
    JFreeChart retChart = super.getChart();

    // Creation of the graph if it not already exist
    if (null == retChart) {

        // Creation of the plot
        SpiderWebPlot plot = new SpiderWebPlot(mDataset);

        // Creation of the picture. The plot is inside the picture
        retChart = new JFreeChart(mTitle, TextTitle.DEFAULT_FONT, plot, false);

        // Display of the legend
        if (showLegend) {
            LegendTitle legendtitle = new LegendTitle(plot);
            legendtitle.setPosition(RectangleEdge.BOTTOM);
            retChart.addSubtitle(legendtitle);
        }

        // Definition of the style of the three first draw in the spiderWEbPlot.
        // This three first draw represent the scale for the mark 1.0, 2.0 and 3.0 in the plot
        // First we define the style
        final float miterLimit = 10.0f;
        final float[] dashPattern = { 5.0f, 3.0f };
        BasicStroke dash = new BasicStroke(1.0f, BasicStroke.CAP_SQUARE, // End cap
                BasicStroke.JOIN_MITER, // Join style
                miterLimit, // Miter limit
                dashPattern, // Dash pattern
                0.0f);
        // We associate this style to the draw
        plot.setSeriesPaint(0, new Color(WebMessages.getInt("kiviat.color.1")));
        plot.setSeriesOutlineStroke(0, dash);
        plot.setSeriesPaint(1, new Color(WebMessages.getInt("kiviat.color.2")));
        plot.setSeriesOutlineStroke(1, dash);
        plot.setSeriesPaint(2, new Color(WebMessages.getInt("kiviat.color.3")));
        plot.setSeriesOutlineStroke(2, dash);

        // Define the gap what is draw and the border of the plot
        plot.setInteriorGap(DEFAULT_GAP);

        // Define the style of the line stroke
        plot.setBaseSeriesOutlineStroke(new BasicStroke(2.0f));

        // The max value put in the plot (for the scale)
        plot.setMaxValue(SCALE_MAX_VALUE);

        // Indicate if we want fill the inner of the draw
        plot.setWebFilled(FILL_RADAR);

        if (!showBackground) {
            // Set the background of the picture to white
            retChart.setBackgroundPaint(Color.WHITE);

            // Set the border of the plot to white
            plot.setOutlinePaint(Color.WHITE);
        }
        super.setChart(retChart);
    }
    return retChart;
}

From source file:com.romraider.logger.ecu.ui.handler.graph.GraphUpdateHandler.java

private synchronized void addToCombined(LoggerData loggerData) {
    if (combinedChartPanel == null) {
        combinedChartPanel = new ChartPanel(createXYLineChart(loggerData, null, true), false, true, true, true,
                true);// w w  w. j av  a  2 s . com
        LegendTitle legendTitle = new LegendTitle(combinedChartPanel.getChart().getXYPlot());
        legendTitle.setItemPaint(WHITE);
        combinedChartPanel.getChart().addLegend(legendTitle);
        combinedChartPanel.setMinimumSize(new Dimension(500, 400));
        combinedChartPanel.setPreferredSize(new Dimension(500, 400));
        graphPanel.add(combinedChartPanel);
    }
    XYPlot plot = combinedChartPanel.getChart().getXYPlot();
    plot.setDataset(counter, new XYSeriesCollection(seriesMap.get(loggerData)));
    plot.setRenderer(counter, new StandardXYItemRenderer());
    datasetIndexes.put(loggerData, counter++);
}

From source file:com.xilinx.kintex7.PowerDial.java

public void createDial() {
    plot = new MeterPlot();
    dset = new DefaultValueDataset(0);
    plot.setUnits("Watts");
    plot.setRange(new Range(1, 10));
    plot.addInterval(new MeterInterval("Acceptable", new Range(1.0, 6.0), Color.lightGray,
            new BasicStroke(2.0f), Color.GREEN));
    plot.addInterval(new MeterInterval("Warning", new Range(6.0, 8.0), Color.lightGray, new BasicStroke(2.0f),
            Color.YELLOW));/* w  w w .  j ava  2  s. c  om*/
    plot.addInterval(new MeterInterval("Dangerous", new Range(8.0, 10.0), Color.lightGray,
            new BasicStroke(2.0f), Color.RED));

    //sets different marks
    for (int i = 0; i < 10; i += 1) {
        if (i == 0)
            plot.addInterval(
                    new MeterInterval("", new Range(1, 1), Color.lightGray, new BasicStroke(2.0f), null));
        else
            plot.addInterval(
                    new MeterInterval("", new Range(i, i), Color.lightGray, new BasicStroke(2.0f), null));
    }
    plot.setNeedlePaint(Color.darkGray);
    plot.setDialBackgroundPaint(Color.white);
    plot.setDialOutlinePaint(Color.gray);
    plot.setDialShape(DialShape.PIE);
    plot.setMeterAngle(180);
    plot.setTickLabelsVisible(true);
    plot.setTickLabelFont(new Font("Dialog", Font.BOLD, 10));
    plot.setTickLabelPaint(Color.DARK_GRAY);
    plot.setTickSize(10.0);
    plot.setTickPaint(Color.lightGray);
    plot.setValuePaint(Color.BLACK);
    plot.setDataset(dset);

    LegendItemCollection legendItemsOld = plot.getLegendItems();
    final LegendItemCollection legendItemsNew = new LegendItemCollection();

    for (int i = 0; i < 3; i++) {
        LegendItem item = legendItemsOld.get(i);
        item.setLabelPaint(Color.WHITE);
        legendItemsNew.add(item);
    }

    LegendItemSource source = new LegendItemSource() {
        LegendItemCollection lic = new LegendItemCollection();
        {
            lic.addAll(legendItemsNew);
        }

        @Override
        public LegendItemCollection getLegendItems() {
            return lic;
        }
    };

    chart = new JFreeChart(plot);
    chart.addLegend(new LegendTitle(source));
    chart.removeLegend();
    chart.setTitle("");
    //chart.setBackgroundPaint(new GradientPaint(0,0,new Color(139,137,137),0,height,Color.BLUE ));
    //
    chart.getTitle().setPaint(Color.white);
    plot.setValueFont(new Font("Dialog", Font.BOLD, 14));
    //chartpanel = new ChartPanel(chart);
}

From source file:org.exist.xquery.modules.jfreechart.JFreeChartFactory.java

/**
 *  Create JFreeChart graph using the supplied parameters.
 *
 * @param chartType One of the many chart types.
 * @param conf      Chart configuration/*ww w .j  a  va 2 s.  c  om*/
 * @param is        Inputstream containing chart data
 * @return          Initialized chart or NULL in case of issues.
 * @throws IOException Thrown when a problem is reported while parsing XML data.
 */
public static JFreeChart createJFreeChart(String chartType, Configuration conf, InputStream is)
        throws XPathException {

    logger.debug("Generating " + chartType);

    // Currently two dataset types supported
    CategoryDataset categoryDataset = null;
    PieDataset pieDataset = null;

    try {
        if ("PieChart".equals(chartType) || "PieChart3D".equals(chartType) || "RingChart".equals(chartType)) {
            logger.debug("Reading XML PieDataset");
            pieDataset = DatasetReader.readPieDatasetFromXML(is);

        } else {
            logger.debug("Reading XML CategoryDataset");
            categoryDataset = DatasetReader.readCategoryDatasetFromXML(is);
        }

    } catch (IOException ex) {
        throw new XPathException(ex.getMessage());

    } finally {
        try {
            is.close();
        } catch (IOException ex) {
            //
        }
    }

    // Return chart
    JFreeChart chart = null;

    // Big chart type switch
    if ("AreaChart".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createAreaChart(conf.getTitle(), conf.getCategoryAxisLabel(),
                conf.getValueAxisLabel(), categoryDataset, conf.getOrientation(), conf.isGenerateLegend(),
                conf.isGenerateTooltips(), conf.isGenerateUrls());

        setCategoryChartParameters(chart, conf);

    } else if ("BarChart".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createBarChart(conf.getTitle(), conf.getCategoryAxisLabel(),
                conf.getValueAxisLabel(), categoryDataset, conf.getOrientation(), conf.isGenerateLegend(),
                conf.isGenerateTooltips(), conf.isGenerateUrls());

        setCategoryChartParameters(chart, conf);

    } else if ("BarChart3D".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createBarChart3D(conf.getTitle(), conf.getCategoryAxisLabel(),
                conf.getValueAxisLabel(), categoryDataset, conf.getOrientation(), conf.isGenerateLegend(),
                conf.isGenerateTooltips(), conf.isGenerateUrls());

        setCategoryChartParameters(chart, conf);

    } else if ("LineChart".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createLineChart(conf.getTitle(), conf.getCategoryAxisLabel(),
                conf.getValueAxisLabel(), categoryDataset, conf.getOrientation(), conf.isGenerateLegend(),
                conf.isGenerateTooltips(), conf.isGenerateUrls());

        setCategoryChartParameters(chart, conf);

    } else if ("LineChart3D".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createLineChart3D(conf.getTitle(), conf.getCategoryAxisLabel(),
                conf.getValueAxisLabel(), categoryDataset, conf.getOrientation(), conf.isGenerateLegend(),
                conf.isGenerateTooltips(), conf.isGenerateUrls());

        setCategoryChartParameters(chart, conf);

    } else if ("MultiplePieChart".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createMultiplePieChart(conf.getTitle(), categoryDataset, conf.getOrder(),
                conf.isGenerateLegend(), conf.isGenerateTooltips(), conf.isGenerateUrls());

        setPieChartParameters(chart, conf);

    } else if ("MultiplePieChart3D".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createMultiplePieChart3D(conf.getTitle(), categoryDataset, conf.getOrder(),
                conf.isGenerateLegend(), conf.isGenerateTooltips(), conf.isGenerateUrls());

        setPieChartParameters(chart, conf);

    } else if ("PieChart".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createPieChart(conf.getTitle(), pieDataset, conf.isGenerateLegend(),
                conf.isGenerateTooltips(), conf.isGenerateUrls());

        setPieChartParameters(chart, conf);

    } else if ("PieChart3D".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createPieChart3D(conf.getTitle(), pieDataset, conf.isGenerateLegend(),
                conf.isGenerateTooltips(), conf.isGenerateUrls());

        setPieChartParameters(chart, conf);

    } else if ("RingChart".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createRingChart(conf.getTitle(), pieDataset, conf.isGenerateLegend(),
                conf.isGenerateTooltips(), conf.isGenerateUrls());

        setPieChartParameters(chart, conf);
    } else if ("SpiderWebChart".equalsIgnoreCase(chartType)) {
        SpiderWebPlot plot = new SpiderWebPlot(categoryDataset);
        if (conf.isGenerateTooltips()) {
            plot.setToolTipGenerator(new StandardCategoryToolTipGenerator());
        }
        chart = new JFreeChart(conf.getTitle(), JFreeChart.DEFAULT_TITLE_FONT, plot, false);

        if (conf.isGenerateLegend()) {
            LegendTitle legend = new LegendTitle(plot);
            legend.setPosition(RectangleEdge.BOTTOM);
            chart.addSubtitle(legend);
        } else {
            TextTitle subTitle = new TextTitle(" ");
            subTitle.setPosition(RectangleEdge.BOTTOM);
            chart.addSubtitle(subTitle);
        }

        setCategoryChartParameters(chart, conf);

    } else if ("StackedAreaChart".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createStackedAreaChart(conf.getTitle(), conf.getCategoryAxisLabel(),
                conf.getValueAxisLabel(), categoryDataset, conf.getOrientation(), conf.isGenerateLegend(),
                conf.isGenerateTooltips(), conf.isGenerateUrls());

        setCategoryChartParameters(chart, conf);

    } else if ("StackedBarChart".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createStackedBarChart(conf.getTitle(), conf.getDomainAxisLabel(),
                conf.getRangeAxisLabel(), categoryDataset, conf.getOrientation(), conf.isGenerateLegend(),
                conf.isGenerateTooltips(), conf.isGenerateUrls());

        setCategoryChartParameters(chart, conf);

    } else if ("StackedBarChart3D".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createStackedBarChart3D(conf.getTitle(), conf.getCategoryAxisLabel(),
                conf.getValueAxisLabel(), categoryDataset, conf.getOrientation(), conf.isGenerateLegend(),
                conf.isGenerateTooltips(), conf.isGenerateUrls());

        setCategoryChartParameters(chart, conf);

    } else if ("WaterfallChart".equalsIgnoreCase(chartType)) {
        chart = ChartFactory.createWaterfallChart(conf.getTitle(), conf.getCategoryAxisLabel(),
                conf.getValueAxisLabel(), categoryDataset, conf.getOrientation(), conf.isGenerateLegend(),
                conf.isGenerateTooltips(), conf.isGenerateUrls());

        setCategoryChartParameters(chart, conf);
    } else {
        logger.error("Illegal chartype. Choose one of " + "AreaChart BarChart BarChart3D LineChart LineChart3D "
                + "MultiplePieChart MultiplePieChart3D PieChart PieChart3D "
                + "RingChart SpiderWebChart StackedAreaChart StackedBarChart "
                + "StackedBarChart3D WaterfallChart");
    }

    setCommonParameters(chart, conf);

    return chart;
}

From source file:ec.nbdemetra.ui.chart3d.functions.Functions2DChart.java

private JFreeChart createChart() {
    XYPlot plot = new XYPlot();

    plot.setDataset(0, Charts.emptyXYDataset());
    plot.setRenderer(0, functionRenderer);
    plot.mapDatasetToDomainAxis(0, 0);//from  w  w  w . j av  a  2 s  . c  o  m
    plot.mapDatasetToRangeAxis(0, 0);

    plot.setDataset(1, Charts.emptyXYDataset());
    plot.setRenderer(1, optimumRenderer);
    plot.mapDatasetToDomainAxis(1, 0);
    plot.mapDatasetToRangeAxis(1, 0);

    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

    JFreeChart result = new JFreeChart("", TsCharts.CHART_TITLE_FONT, plot, false);

    LegendTitle legend = new LegendTitle(result.getPlot());
    legend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0));
    legend.setFrame(new LineBorder());
    legend.setBackgroundPaint(Color.white);
    legend.setPosition(RectangleEdge.BOTTOM);
    result.addLegend(legend);

    result.setPadding(TsCharts.CHART_PADDING);
    return result;
}

From source file:org.ash.history.TopActivityPreview.java

/**
 * Add legend to chart panel./*from  w  ww  .  j  a v a2 s . co m*/
 * 
 * @param fontSize
 */
public void addLegend(int fontSize) {

    LegendTitle legend = new LegendTitle(chart.getPlot());

    BlockContainer wrapper = new BlockContainer(new BorderArrangement());
    wrapper.setFrame(new BlockBorder(1.0, 1.0, 1.0, 1.0));

    BlockContainer itemss = legend.getItemContainer();
    itemss.setPadding(2, 10, 5, 2);
    wrapper.add(itemss);
    legend.setWrapper(wrapper);

    legend.setItemFont(new Font(LegendTitle.DEFAULT_ITEM_FONT.getFontName(),
            LegendTitle.DEFAULT_ITEM_FONT.getStyle(), fontSize));

    legend.setPosition(RectangleEdge.RIGHT);
    legend.setHorizontalAlignment(HorizontalAlignment.LEFT);

    chart.addSubtitle(legend);

}

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);// ww w . j  a v a2 s . c o m
    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:de.laures.cewolf.util.Renderer.java

/**
 * Renders a legend//from w  ww .ja  v  a 2  s .com
 * @param cd the chart iamge to be rendred
 * @return the rendered image
 * @throws CewolfException
 */
private static RenderedImage renderLegend(ChartImage cd, Object c) throws CewolfException {
    try {
        JFreeChart chart = (JFreeChart) c;
        final int width = cd.getWidth();
        final int height = cd.getHeight();
        LegendTitle legend = getLegend(chart);
        boolean haslegend = true;

        // with JFreeChart v0.9.20, the only way to get a valid legend,
        // is either to retrieve it from the chart or to assign a new
        // one to the chart. In the case where the chart has no legend,
        // a new one must be assigned, but just for rendering. After, we
        // have to reset the legend to null in the chart.
        if (null == legend) {
            haslegend = false;
            legend = new LegendTitle(chart.getPlot());
        }
        legend.setPosition(RectangleEdge.BOTTOM);
        BufferedImage bimage = ImageHelper.createImage(width, height);
        Graphics2D g = bimage.createGraphics();
        g.setColor(Color.white);
        g.fillRect(0, 0, width, height);
        legend.arrange(g, new RectangleConstraint(width, height));
        legend.draw(g, new Rectangle(width, height));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
        param.setQuality(1.0f, true);
        encoder.encode(bimage, param);
        out.close();

        // if the chart had no legend, reset it to null in order to give back the
        // chart in the state we received it.
        if (!haslegend) {
            removeLegend(chart);
        }

        return new RenderedImage(out.toByteArray(), "image/jpeg",
                new ChartRenderingInfo(new StandardEntityCollection()));
    } catch (IOException ioex) {
        log.error(ioex);
        throw new ChartRenderingException(ioex.getMessage(), ioex);
    }
}