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:com.mxgraph.examples.swing.chart.BarChartDemo1.java

public static JFreeChart createChart1(CategoryDataset dataset) {

    // create the chart...
    JFreeChart chart = ChartFactory.createBarChart("", // chart title
            "X-value", // domain axis label
            "Y-value", // range axis label
            dataset, // data
            PlotOrientation.HORIZONTAL, // orientation
            true, // include legend
            true, // tooltips?
            false // URLs?
    );//  ww  w.java  2  s  .c o m

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

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

    // get a reference to the plot for further customisation...
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);

    CategoryAxis categoryAxis = plot.getDomainAxis();
    categoryAxis.setCategoryMargin(0.1);//
    categoryAxis.setUpperMargin(0.02);
    categoryAxis.setLowerMargin(0.02);

    // ******************************************************************
    //  More than 150 demo applications are included with the JFreeChart
    //  Developer Guide...for more information, see:
    //
    //  >   http://www.object-refinery.com/jfreechart/guide.html
    //
    // ******************************************************************

    // set the range axis to display integers only...
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setUpperMargin(0.10);
    // disable bar outlines...
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(true);
    renderer.setBaseItemLabelsVisible(true);
    renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    // set up gradient paints for series...
    GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, new Color(0, 0, 64));
    GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.green, 0.0f, 0.0f, new Color(0, 64, 0));
    GradientPaint gp2 = new GradientPaint(0.0f, 0.0f, Color.red, 0.0f, 0.0f, new Color(64, 0, 0));
    renderer.setSeriesPaint(0, gp0);
    renderer.setSeriesPaint(1, gp1);
    renderer.setSeriesPaint(2, gp2);

    renderer.setBasePositiveItemLabelPosition(
            new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
    renderer.setItemLabelAnchorOffset(10D);
    renderer.setItemLabelFont(new Font("", Font.PLAIN, 12));
    renderer.setItemLabelsVisible(true);

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 180));

    // OPTIONAL CUSTOMISATION COMPLETED.      

    chart.getTitle().setFont(new Font("", Font.BOLD, 16));//

    //
    domainAxis.setLabelFont(new Font("", Font.BOLD, 14));
    //
    domainAxis.setTickLabelFont(new Font("", Font.PLAIN, 10));

    //
    rangeAxis.setLabelFont(new Font("", Font.BOLD, 15));

    chart.getLegend().setItemFont(new Font("", Font.BOLD, 15));

    /**
     *  chart.getTitle().setFont(new Font("",Font.BOLD,20));//
            
    //
    domainAxis.setLabelFont(new Font("",Font.BOLD,14));
    //
    domainAxis.setTickLabelFont(new Font("",Font.BOLD,12));
    //
    rangeAxis.setLabelFont(new Font("",Font.BOLD,15));
            
    chart.getLegend().setItemFont(new Font("", Font.BOLD, 15));
     */
    return chart;

}

From source file:com.rapidminer.gui.viewer.ROCChartPlotter.java

private JFreeChart createChart(XYDataset dataset) {
    // create the chart...
    JFreeChart chart = ChartFactory.createXYLineChart(null, // chart title
            null, // x axis label
            null, // y axis label
            dataset, // data
            PlotOrientation.VERTICAL, true, // include legend
            true, // tooltips
            false // urls
    );/*w  w w  .  j a  v a 2s. c  o m*/

    chart.setBackgroundPaint(Color.white);

    // get a reference to the plot for further customisation...
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

    ValueAxis valueAxis = plot.getRangeAxis();
    valueAxis.setLabelFont(PlotterAdapter.LABEL_FONT_BOLD);
    valueAxis.setTickLabelFont(PlotterAdapter.LABEL_FONT);

    ValueAxis domainAxis = plot.getDomainAxis();
    domainAxis.setLabelFont(PlotterAdapter.LABEL_FONT_BOLD);
    domainAxis.setTickLabelFont(PlotterAdapter.LABEL_FONT);

    DeviationRenderer renderer = new DeviationRenderer(true, false);
    Stroke stroke = new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND);
    if (dataset.getSeriesCount() == 1) {
        renderer.setSeriesStroke(0, stroke);
        renderer.setSeriesPaint(0, Color.RED);
        renderer.setSeriesFillPaint(0, Color.RED);
    } else if (dataset.getSeriesCount() == 2) {
        renderer.setSeriesStroke(0, stroke);
        renderer.setSeriesPaint(0, Color.RED);
        renderer.setSeriesFillPaint(0, Color.RED);

        renderer.setSeriesStroke(1, stroke);
        renderer.setSeriesPaint(1, Color.BLUE);
        renderer.setSeriesFillPaint(1, Color.BLUE);
    } else {
        for (int i = 0; i < dataset.getSeriesCount(); i++) {
            renderer.setSeriesStroke(i, stroke);
            Color color = colorProvider.getPointColor((double) i / (double) (dataset.getSeriesCount() - 1));
            renderer.setSeriesPaint(i, color);
            renderer.setSeriesFillPaint(i, color);
        }
    }
    renderer.setAlpha(0.12f);
    plot.setRenderer(renderer);

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

From source file:net.sf.fspdfs.chartthemes.spring.GenericChartTheme.java

protected void setChartLegend(JFreeChart jfreeChart, Integer baseFontSize) {

    //The legend visibility is already taken into account in the jfreeChart object's constructor

    LegendTitle legend = jfreeChart.getLegend();
    if (legend != null) {
        Font themeLegendFont = getFont(
                (JRFont) getDefaultValue(defaultChartPropertiesMap, ChartThemesConstants.LEGEND_FONT),
                getChart().getLegendFont(), baseFontSize);
        legend.setItemFont(themeLegendFont);

        Color legendForecolor = getChart().getOwnLegendColor() != null ? getChart().getOwnLegendColor()
                : (getDefaultValue(defaultChartPropertiesMap, ChartThemesConstants.LEGEND_FORECOLOR) != null
                        ? (Color) getDefaultValue(defaultChartPropertiesMap,
                                ChartThemesConstants.LEGEND_FORECOLOR)
                        : getChart().getLegendColor());
        if (legendForecolor != null)
            legend.setItemPaint(legendForecolor);

        Color legendBackcolor = getChart().getOwnLegendBackgroundColor() != null
                ? getChart().getOwnLegendBackgroundColor()
                : (getDefaultValue(defaultChartPropertiesMap, ChartThemesConstants.LEGEND_BACKCOLOR) != null
                        ? (Color) getDefaultValue(defaultChartPropertiesMap,
                                ChartThemesConstants.LEGEND_BACKCOLOR)
                        : getChart().getLegendBackgroundColor());
        if (legendBackcolor != null)
            legend.setBackgroundPaint(legendBackcolor);

        BlockFrame frame = (BlockFrame) getDefaultValue(defaultChartPropertiesMap,
                ChartThemesConstants.LEGEND_FRAME);
        if (frame != null)
            legend.setFrame(frame);//from   www.j a  va 2s  .c  o  m

        HorizontalAlignment defaultLegendHAlignment = (HorizontalAlignment) getDefaultValue(
                defaultChartPropertiesMap, ChartThemesConstants.LEGEND_HORIZONTAL_ALIGNMENT);
        if (defaultLegendHAlignment != null)
            legend.setHorizontalAlignment(defaultLegendHAlignment);

        VerticalAlignment defaultLegendVAlignment = (VerticalAlignment) getDefaultValue(
                defaultChartPropertiesMap, ChartThemesConstants.LEGEND_VERTICAL_ALIGNMENT);
        if (defaultLegendVAlignment != null)
            legend.setVerticalAlignment(defaultLegendVAlignment);

        RectangleInsets defaultLegendPadding = (RectangleInsets) getDefaultValue(defaultChartPropertiesMap,
                ChartThemesConstants.LEGEND_PADDING);
        RectangleInsets legendPadding = legend.getPadding() != null ? legend.getPadding()
                : defaultLegendPadding;
        if (legendPadding != null)
            legend.setPadding(legendPadding);

        RectangleEdge defaultLegendPosition = (RectangleEdge) getDefaultValue(defaultChartPropertiesMap,
                ChartThemesConstants.LEGEND_POSITION);
        if (getEdge(getChart().getLegendPositionValue(), defaultLegendPosition) != null)
            legend.setPosition(getEdge(getChart().getLegendPositionValue(), defaultLegendPosition));

    }
}

From source file:net.sf.fspdfs.chartthemes.simple.SimpleChartTheme.java

protected void setChartLegend(JFreeChart jfreeChart) {
    //The legend visibility is already taken into account in the jfreeChart object's constructor
    LegendTitle legend = jfreeChart.getLegend();
    if (legend != null) {
        LegendSettings legendSettings = getLegendSettings();
        JRBaseFont font = new JRBaseFont();
        JRFontUtil.copyNonNullOwnProperties(legendSettings.getFont(), font);
        JRFontUtil.copyNonNullOwnProperties(getChart().getLegendFont(), font);
        font = new JRBaseFont(getChart(), font);
        legend.setItemFont(JRFontUtil.getAwtFont(font, getLocale()));

        Paint forePaint = getChart().getOwnLegendColor();
        if (forePaint == null && legendSettings.getForegroundPaint() != null) {
            forePaint = legendSettings.getForegroundPaint().getPaint();
        }//from  w  ww. j a v a 2 s  .  co  m
        if (forePaint == null) {
            forePaint = getChart().getLegendColor();
        }
        if (forePaint != null)
            legend.setItemPaint(forePaint);

        Paint backPaint = getChart().getOwnLegendBackgroundColor();
        if (backPaint == null && legendSettings.getBackgroundPaint() != null) {
            backPaint = legendSettings.getBackgroundPaint().getPaint();
        }
        if (backPaint == null) {
            backPaint = getChart().getLegendBackgroundColor();
        }
        if (backPaint != null)
            legend.setBackgroundPaint(backPaint);

        BlockFrame blockFrame = legendSettings.getBlockFrame();
        if (blockFrame != null)
            legend.setFrame(blockFrame);

        HorizontalAlignment hAlign = legendSettings.getHorizontalAlignment();
        if (hAlign != null)
            legend.setHorizontalAlignment(hAlign);

        VerticalAlignment vAlign = legendSettings.getVerticalAlignment();
        if (vAlign != null)
            legend.setVerticalAlignment(vAlign);

        RectangleInsets padding = legendSettings.getPadding();
        if (padding != null)
            legend.setPadding(padding);

        legend.setPosition(getEdge(getChart().getLegendPositionValue(),
                getEdge(legendSettings.getPositionValue(), RectangleEdge.BOTTOM)));
    }
}

From source file:eu.planets_project.tb.impl.chart.ExperimentChartServlet.java

public JFreeChart createWallclockChart(String expId) {
    ExperimentPersistencyRemote edao = ExperimentPersistencyImpl.getInstance();
    long eid = Long.parseLong(expId);
    log.info("Building experiment chart for eid = " + eid);
    Experiment exp = edao.findExperiment(eid);

    final DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    final String expName = exp.getExperimentSetup().getBasicProperties().getExperimentName();

    boolean hasSuccesses = false;
    boolean hasFails = false;

    for (BatchExecutionRecordImpl batch : exp.getExperimentExecutable().getBatchExecutionRecords()) {
        int i = 1;
        List<ExecutionRecordImpl> runs = new ArrayList<ExecutionRecordImpl>(batch.getRuns());
        Collections.sort(runs, new RunComparator());
        for (ExecutionRecordImpl exr : runs) {
            //log.info("Found Record... "+exr+" stages: "+exr.getStages());
            if (exr != null && exr.getStages() != null) {
                // Look up the object, so we can get the name.
                DigitalObjectRefBean dh = new DataHandlerImpl().get(exr.getDigitalObjectReferenceCopy());
                String dobName = "Object " + i;
                if (dh != null)
                    dobName = dh.getName();

                ResultsForDigitalObjectBean res = new ResultsForDigitalObjectBean(
                        exr.getDigitalObjectReferenceCopy());
                Double time = null;
                boolean success = false;
                // First, attempt to pull from stage records:
                // FIXME: Note that this record is really at the wrong level.
                /*//from ww w .  j  a v a2s  . co  m
                if( exr.getStages().size() == 1 ) {
                for( ExecutionStageRecordImpl exsr : exr.getStages() ) {
                    Double stageTime = exsr.getDoubleMeasurement( TecRegMockup.PROP_SERVICE_TIME );
                    if( stageTime != null ) {
                        time = stageTime;
                        success = exsr.isMarkedAsSuccessful();
                    }
                }
                }
                */
                // Pick up from record duration:
                if (time == null && res.getExecutionDuration() != null) {
                    //convert from milli seconds to seconds
                    time = (double) res.getExecutionDuration() / 1000.0;
                    success = res.getHasExecutionSucceededOK();
                }
                log.info("Found DOB: {" + exr.getDigitalObjectReferenceCopy() + "} {" + dobName + "} w/ time "
                        + time);
                if (res.getExecutionRecord() != null)
                    log.info("Timing: " + res.getExecutionRecord().getStartDate() + " "
                            + res.getExecutionRecord().getEndDate());
                if (time != null) {
                    if (success) {
                        dataset.addValue(time, "Succeeded", dobName);
                        hasSuccesses = true;
                    } else {
                        dataset.addValue(time, "Failed", dobName);
                        hasFails = true;
                    }
                }
            }
            // Increment, for the next run.
            i++;
        }
    }
    int si = dataset.getRowIndex("Succeeded");
    int ri = dataset.getRowIndex("Failed");

    // Create the chart.
    JFreeChart chart = ChartFactory.createStackedBarChart(null, "Digital Object", "Time [s]", dataset,
            PlotOrientation.VERTICAL, true, true, false);

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

    // get a reference to the plot for further customisation...
    final CategoryPlot plot = chart.getCategoryPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.gray);
    plot.setRangeGridlinePaint(Color.gray);

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

    // disable bar outlines...
    final BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(true);
    renderer.setShadowVisible(false);
    renderer.setBarPainter(new StandardBarPainter());

    // set up gradient paints for series...
    final GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.green, 0.0f, 0.0f,
            new Color(0.0f, 0.9f, 0.0f));
    final GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.red, 0.0f, 0.0f, new Color(0.9f, 0.0f, 0.0f));
    if (hasSuccesses)
        renderer.setSeriesPaint(si, gp0);
    if (hasFails)
        renderer.setSeriesPaint(ri, gp1);

    // Set the tooltips...
    //renderer.setBaseItemURLGenerator(new StandardCategoryURLGenerator("xy_chart.jsp","series","section"));
    renderer.setBaseToolTipGenerator(new MeasurementToolTipGenerator());

    final CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 4.0));

    // More settings
    chart.getRenderingHints().put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    // Remove the border, as the SVG renderer has problems with the text overflowing.
    chart.getLegend().setBorder(0.0, 0.0, 0.0, 0.0);
    // Remove the padding between the axes and the plot:
    chart.getPlot().setInsets(new RectangleInsets(0.0, 0.0, 0.0, 0.0));
    // Set a gradient fill, fading towards the top:
    final GradientPaint gpb0 = new GradientPaint(0.0f, 0.0f, new Color(245, 245, 245), 0.0f, 0.0f, Color.white);
    chart.getPlot().setBackgroundPaint(gpb0);

    return chart;
}

From source file:mil.tatrc.physiology.utilities.csv.plots.MultiPlotter.java

protected void formatMultiPlot(PlotJob job, JFreeChart chart, XYSeriesCollection dataSet1,
        XYSeriesCollection dataSet2) {/*from   ww w  .  ja v a2  s.  c  o  m*/
    Color[] blueColors = { Color.blue, Color.cyan, new Color(0, 160, 255), new Color(0, 100, 255),
            new Color(0, 160, 255), new Color(14, 0, 145), new Color(70, 105, 150) };
    Color[] redColors = { Color.red, Color.magenta, new Color(255, 0, 100), new Color(255, 0, 160), Color.pink,
            new Color(145, 0, 0), new Color(132, 58, 58) };
    Color[] variedColors = { Color.red, Color.blue, Color.green, Color.orange, Color.magenta, Color.cyan,
            Color.gray, new Color(255, 165, 0), new Color(42, 183, 136), new Color(87, 158, 186) };
    XYPlot plot = (XYPlot) chart.getPlot();
    XYLineAndShapeRenderer renderer1 = (XYLineAndShapeRenderer) plot.getRenderer();
    BasicStroke wideLine = new BasicStroke(2.0f);

    //For Scientific notation
    NumberFormat formatter = new DecimalFormat("0.######E0");

    for (int i = 0; i < plot.getDomainAxisCount(); i++) {
        plot.getDomainAxis(i).setLabelFont(new Font("SansSerif", Font.PLAIN, job.fontSize));
        plot.getDomainAxis(i).setTickLabelFont(new Font("SansSerif", Font.PLAIN, 15));
        plot.getDomainAxis(i).setLabelPaint(job.bgColor == Color.red ? Color.white : Color.black);
        plot.getDomainAxis(i).setTickLabelPaint(job.bgColor == Color.red ? Color.white : Color.black);
    }
    for (int i = 0; i < plot.getRangeAxisCount(); i++) {
        plot.getRangeAxis(i).setLabelFont(new Font("SansSerif", Font.PLAIN, job.fontSize));
        plot.getRangeAxis(i).setTickLabelFont(new Font("SansSerif", Font.PLAIN, 15));
        plot.getRangeAxis(i).setLabelPaint(job.bgColor == Color.red ? Color.white : Color.black);
        plot.getRangeAxis(i).setTickLabelPaint(job.bgColor == Color.red ? Color.white : Color.black);
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(i);
        rangeAxis.setNumberFormatOverride(formatter);
    }

    //White background outside of plottable area
    chart.setBackgroundPaint(job.bgColor);

    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.black);
    plot.setRangeGridlinePaint(Color.black);

    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    chart.getLegend().setItemFont(new Font("SansSerif", Font.PLAIN, 15));
    chart.getTitle().setFont(new Font("SansSerif", Font.PLAIN, job.fontSize));
    chart.getTitle().setPaint(job.bgColor == Color.red ? Color.white : Color.black);

    //If there is only one Y axis, we just need to color the data series differently
    if (job.Y2headers == null || job.Y2headers.isEmpty()) {
        for (int i = 0, cIndex = 0; i < dataSet1.getSeriesCount(); i++, cIndex++) {
            renderer1.setSeriesStroke(i, wideLine);
            renderer1.setBaseShapesVisible(false);
            if (cIndex > 9)
                cIndex = 0;
            renderer1.setSeriesFillPaint(i, variedColors[cIndex]);
            renderer1.setSeriesPaint(i, variedColors[cIndex]);
        }
    }
    //If there are 2 Y axes, we should color the axes to correspond with the data so it isn't (as) confusing
    else {
        StandardXYItemRenderer renderer2 = new StandardXYItemRenderer();
        plot.setRenderer(1, renderer2);

        for (int i = 0, cIndex = 0; i < dataSet1.getSeriesCount(); i++, cIndex++) {
            renderer1.setSeriesStroke(i, wideLine);
            renderer1.setBaseShapesVisible(false);
            if (cIndex > 6)
                cIndex = 0;
            renderer1.setSeriesFillPaint(i, redColors[cIndex]);
            renderer1.setSeriesPaint(i, redColors[cIndex]);
        }
        for (int i = 0, cIndex = 0; i < dataSet2.getSeriesCount(); i++, cIndex++) {
            renderer2.setSeriesStroke(i, wideLine);
            renderer2.setBaseShapesVisible(false);
            if (cIndex > 6)
                cIndex = 0;
            renderer2.setSeriesFillPaint(i, blueColors[cIndex]);
            renderer2.setSeriesPaint(i, blueColors[cIndex]);
        }
        plot.getRangeAxis(0).setLabelPaint(redColors[0]);
        plot.getRangeAxis(0).setTickLabelPaint(redColors[0]);
        plot.getRangeAxis(1).setLabelPaint(blueColors[0]);
        plot.getRangeAxis(1).setTickLabelPaint(blueColors[0]);
    }
}

From source file:com.manydesigns.portofino.chart.Chart1DGenerator.java

public JFreeChart generate(ChartDefinition chartDefinition, Persistence persistence, Locale locale) {
    DefaultPieDataset dataset = new DefaultPieDataset();
    java.util.List<Object[]> result;
    String query = chartDefinition.getQuery();
    logger.info(query);/*from   w  w  w  .  j  a v a  2s  . com*/
    Session session = persistence.getSession(chartDefinition.getDatabase());
    result = QueryUtils.runSql(session, query);
    for (Object[] current : result) {
        ComparableWrapper key = new ComparableWrapper((Comparable) current[0]);
        dataset.setValue(key, (Number) current[1]);
        if (current.length > 2) {
            key.setLabel(current[2].toString());
        }
    }

    JFreeChart chart = createChart(chartDefinition, dataset);

    chart.setAntiAlias(isAntiAlias());

    // impostiamo il bordo invisibile
    // eventualmente e' il css a fornirne uno
    // eventualmente e' il css a fornirne uno
    chart.setBorderVisible(isBorderVisible());

    // impostiamo il titolo
    TextTitle title = chart.getTitle();
    title.setFont(titleFont);
    title.setMargin(10.0, 0.0, 0.0, 0.0);

    // ottieni il Plot
    PiePlot plot = (PiePlot) chart.getPlot();

    String urlExpression = chartDefinition.getUrlExpression();
    if (!StringUtils.isBlank(urlExpression)) {
        PieURLGenerator urlGenerator = new ChartPieUrlGenerator(urlExpression);
        plot.setURLGenerator(urlGenerator);
    } else {
        plot.setURLGenerator(null);
    }

    // il plot ha sfondo e bordo trasparente
    // (quindi si vede il colore del chart)
    plot.setBackgroundPaint(transparentColor);
    plot.setOutlinePaint(transparentColor);

    // Modifico il toolTip
    // hongliangpan add
    // :?{0}  {1}  {2} ? ,???
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}={1}({2})",
            NumberFormat.getNumberInstance(), new DecimalFormat("0.00%")));
    // {0}={1}({2})
    plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0}"));
    // ?(0.0-1.0)
    // plot.setForegroundAlpha(1.0f);
    // imposta la distanza delle etichette dal plot
    plot.setLabelGap(0.03);
    // plot.setLabelGenerator(new MyPieSectionLabelGenerator());

    // imposta il messaggio se non ci sono dati
    plot.setNoDataMessage(ElementsThreadLocals.getText("no.data.available"));

    plot.setCircular(true);

    plot.setBaseSectionOutlinePaint(Color.BLACK);

    DrawingSupplier supplier = new DesaturatedDrawingSupplier(plot.getDrawingSupplier());
    plot.setDrawingSupplier(supplier);
    // ?
    plot.setForegroundAlpha(1.0f);
    // impostiamo il titolo della legenda
    String legendString = chartDefinition.getLegend();
    Title subtitle = new TextTitle(legendString, legendFont, Color.BLACK, RectangleEdge.BOTTOM,
            HorizontalAlignment.CENTER, VerticalAlignment.CENTER, new RectangleInsets(0, 0, 0, 0));
    subtitle.setMargin(0, 0, 5, 0);
    chart.addSubtitle(subtitle);

    // impostiamo la legenda
    LegendTitle legend = chart.getLegend();
    legend.setBorder(0, 0, 0, 0);
    legend.setItemFont(legendItemFont);
    int legendMargin = 10;
    legend.setMargin(0.0, legendMargin, legendMargin, legendMargin);
    legend.setBackgroundPaint(transparentColor);

    // impostiamo un gradiente orizzontale
    Paint chartBgPaint = new GradientPaint(0, 0, new Color(255, 253, 240), 0, getHeight(), Color.WHITE);
    chart.setBackgroundPaint(chartBgPaint);
    return chart;
}

From source file:net.sf.jasperreports.chartthemes.simple.SimpleChartTheme.java

protected void setChartLegend(JFreeChart jfreeChart) {
    //The legend visibility is already taken into account in the jfreeChart object's constructor
    LegendTitle legend = jfreeChart.getLegend();
    if (legend != null) {
        LegendSettings legendSettings = getLegendSettings();
        JRBaseFont font = new JRBaseFont();
        FontUtil.copyNonNullOwnProperties(legendSettings.getFont(), font);
        FontUtil.copyNonNullOwnProperties(getChart().getLegendFont(), font);
        font = new JRBaseFont(getChart(), font);
        legend.setItemFont(getFontUtil().getAwtFont(font, getLocale()));

        Paint forePaint = getChart().getOwnLegendColor();
        if (forePaint == null && legendSettings.getForegroundPaint() != null) {
            forePaint = legendSettings.getForegroundPaint().getPaint();
        }//ww w  .  ja  v a  2s  .co  m
        if (forePaint == null) {
            forePaint = getChart().getLegendColor();
        }
        if (forePaint != null)
            legend.setItemPaint(forePaint);

        Paint backPaint = getChart().getOwnLegendBackgroundColor();
        if (backPaint == null && legendSettings.getBackgroundPaint() != null) {
            backPaint = legendSettings.getBackgroundPaint().getPaint();
        }
        if (backPaint == null) {
            backPaint = getChart().getLegendBackgroundColor();
        }
        if (backPaint != null)
            legend.setBackgroundPaint(backPaint);

        BlockFrame blockFrame = legendSettings.getBlockFrame();
        if (blockFrame != null)
            legend.setFrame(blockFrame);

        HorizontalAlignment hAlign = legendSettings.getHorizontalAlignment();
        if (hAlign != null)
            legend.setHorizontalAlignment(hAlign);

        VerticalAlignment vAlign = legendSettings.getVerticalAlignment();
        if (vAlign != null)
            legend.setVerticalAlignment(vAlign);

        RectangleInsets padding = legendSettings.getPadding();
        if (padding != null)
            legend.setPadding(padding);

        legend.setPosition(getEdge(getChart().getLegendPositionValue(),
                getEdge(legendSettings.getPositionValue(), RectangleEdge.BOTTOM)));
    }
}

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

@Override
public void updatePlotter() {
    prepareData();/*from  w  w w.j  a v  a 2 s . c  o  m*/

    JFreeChart chart = createChart(this.dataset);

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

    // general plot settings
    XYPlot plot = chart.getXYPlot();
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

    // domain axis
    SymbolAxis axis = null;
    if (this.dataTable.isSupportingColumnWeights()) {
        List<Double> weightList = new LinkedList<>();
        for (int column = 0; column < dataTable.getNumberOfColumns(); column++) {
            if ((!dataTable.isSpecial(column)) && (column != colorColumn)) {
                weightList.add(this.dataTable.getColumnWeight(column));
            }
        }
        double[] weights = new double[weightList.size()];
        int index = 0;
        for (Double d : weightList) {
            weights[index++] = d;
        }
        axis = new WeightBasedSymbolAxis(null, domainAxisMap, weights);
    } else {
        axis = new SymbolAxis(null, domainAxisMap);
    }
    axis.setTickLabelFont(LABEL_FONT);
    axis.setLabelFont(LABEL_FONT_BOLD);

    // rotate labels
    if (isLabelRotating()) {
        axis.setTickLabelsVisible(true);
        axis.setVerticalTickLabels(true);
    }

    chart.getXYPlot().setDomainAxis(axis);

    // renderer
    final ColorizedLineAndShapeRenderer renderer = new ColorizedLineAndShapeRenderer(this.colorMap);
    plot.setRenderer(renderer);

    // legend settings
    if ((colorColumn >= 0) && (this.dataTable.isNominal(colorColumn))) {
        final LegendItemCollection legendItemCollection = new LegendItemCollection();
        for (int i = 0; i < this.dataTable.getNumberOfValues(colorColumn); i++) {
            legendItemCollection.add(new LegendItem(this.dataTable.mapIndex(colorColumn, i), null, null, null,
                    new Rectangle2D.Double(0, 0, 7, 7),
                    getColorProvider()
                            .getPointColor(i / (double) (this.dataTable.getNumberOfValues(colorColumn) - 1)),
                    new BasicStroke(0.75f), Color.GRAY));
        }
        chart.addLegend(new LegendTitle(new LegendItemSource() {

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

        LegendTitle legend = chart.getLegend();
        if (legend != null) {
            legend.setPosition(RectangleEdge.TOP);
            legend.setFrame(BlockBorder.NONE);
            legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
            legend.setItemFont(LABEL_FONT);
        }
    } else if (colorColumn >= 0) {
        chart.addLegend(new LegendTitle(new LegendItemSource() {

            @Override
            public LegendItemCollection getLegendItems() {
                LegendItemCollection itemCollection = new LegendItemCollection();
                itemCollection.add(new LegendItem("Dummy"));
                return itemCollection;
            }
        }) {

            private static final long serialVersionUID = 1288380309936848376L;

            @Override
            public Object draw(java.awt.Graphics2D g2, java.awt.geom.Rectangle2D area,
                    java.lang.Object params) {
                if (dataTable.isDate(colorColumn) || dataTable.isTime(colorColumn)
                        || dataTable.isDateTime(colorColumn)) {
                    drawSimpleDateLegend(g2, (int) (area.getCenterX() - 170), (int) (area.getCenterY() + 7),
                            dataTable, colorColumn, renderer.getMinColorValue(), renderer.getMaxColorValue());
                    return new BlockResult();
                } else {
                    final String minColorString = Tools.formatNumber(renderer.getMinColorValue());
                    final String maxColorString = Tools.formatNumber(renderer.getMaxColorValue());
                    drawSimpleNumericalLegend(g2, (int) (area.getCenterX() - 90), (int) (area.getCenterY() + 7),
                            dataTable.getColumnName(colorColumn), minColorString, maxColorString);
                    return new BlockResult();
                }
            }

            @Override
            public void draw(java.awt.Graphics2D g2, java.awt.geom.Rectangle2D area) {
                draw(g2, area, null);
            }

        });
    }

    // chart panel
    if (panel instanceof AbstractChartPanel) {
        panel.setChart(chart);
    } else {
        panel = new AbstractChartPanel(chart, getWidth(), getHeight() - MARGIN);
        final ChartPanelShiftController controller = new ChartPanelShiftController(panel);
        panel.addMouseListener(controller);
        panel.addMouseMotionListener(controller);
    }

    // ATTENTION: WITHOUT THIS WE GET SEVERE MEMORY LEAKS!!!
    panel.getChartRenderingInfo().setEntityCollection(null);
}