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

/**
 * Sets the colours and gradients to be used when painting the given JFreeChart.
 * //from w ww.  j av  a  2  s .  com
 * @param chart
 *          The JFreeChart to make nice.
 */
public static void makeChartNice(JFreeChart chart) {
    Plot plot = chart.getPlot();
    chart.setBackgroundPaint(null);
    chart.setBorderStroke(new BasicStroke(1f));
    chart.setBorderPaint(new Color(0xDDDDDD));
    chart.setBorderVisible(true);

    // TODO Should we add an option for subtitles, this is where it would go.
    //        TextTitle subTitle = new TextTitle("What's up doc?",
    //             new Font("SansSerif", Font.BOLD, 8));
    //       chart.addSubtitle(subTitle);

    // overall plot
    plot.setOutlinePaint(null);
    plot.setInsets(new RectangleInsets(0, 5, 0, 5)); // also the overall chart panel
    plot.setBackgroundPaint(null);
    plot.setDrawingSupplier(new WabitDrawingSupplier());

    // legend
    LegendTitle legend = chart.getLegend();
    if (legend != null) {
        legend.setBorder(0, 0, 0, 0);
        legend.setBackgroundPaint(null);
        legend.setPadding(2, 2, 2, 2);
    }

    if (plot instanceof CategoryPlot) {
        CategoryPlot cplot = (CategoryPlot) plot;

        CategoryItemRenderer renderer = cplot.getRenderer();
        if (renderer instanceof BarRenderer) {
            BarRenderer brenderer = (BarRenderer) renderer;

            brenderer.setBarPainter(new StandardBarPainter());
            brenderer.setDrawBarOutline(false);
            brenderer.setShadowVisible(false);

            brenderer.setGradientPaintTransformer(
                    new StandardGradientPaintTransformer(GradientPaintTransformType.HORIZONTAL));

        } else if (renderer instanceof LineAndShapeRenderer) {
            // it's all taken care of by WabitDrawingSupplier

        } else {
            logger.warn("I don't know how to make " + renderer + " pretty. Leaving ugly.");
        }

        cplot.setRangeGridlinePaint(Color.BLACK);
        cplot.setRangeGridlineStroke(GRIDLINE_STROKE);

        // axes
        for (int i = 0; i < cplot.getDomainAxisCount(); i++) {
            CategoryAxis axis = cplot.getDomainAxis(i);
            axis.setAxisLineVisible(false);
        }

        for (int i = 0; i < cplot.getRangeAxisCount(); i++) {
            ValueAxis axis = cplot.getRangeAxis(i);
            axis.setAxisLineVisible(false);
        }
    }

    if (plot instanceof MultiplePiePlot) {
        MultiplePiePlot mpplot = (MultiplePiePlot) plot;
        JFreeChart pchart = mpplot.getPieChart();
        PiePlot3DGradient pplot = (PiePlot3DGradient) pchart.getPlot();
        pplot.setBackgroundPaint(null);
        pplot.setOutlinePaint(null);

        pplot.setFaceGradientPaintTransformer(
                new StandardGradientPaintTransformer(GradientPaintTransformType.HORIZONTAL));
        pplot.setSideGradientPaintTransformer(
                new StandardGradientPaintTransformer(GradientPaintTransformType.HORIZONTAL));

        CategoryDataset data = mpplot.getDataset();
        Color[][] colours = WabitDrawingSupplier.SERIES_COLOURS;

        //Set all colours
        for (int i = 0; i < colours.length; i++) {
            if (data.getColumnCount() >= i + 1) {
                pplot.setSectionOutlinePaint(data.getColumnKey(i), null);
                GradientPaint gradient = new GradientPaint(0, 0f, colours[i][0], 100, 0f, colours[i][1]);
                pplot.setSectionPaint(data.getColumnKey(i), gradient);
                gradient = new GradientPaint(0, 0f, colours[i][1], 100, 0f, colours[i][0]);
                pplot.setSidePaint(data.getColumnKey(i), gradient);
            }
        }
    }

    // Tweak the title font size
    chart.getTitle().setFont(chart.getTitle().getFont().deriveFont(14f));
    chart.getTitle().setPadding(5, 0, 5, 0);
    chart.setAntiAlias(true);

    // shrink padding
    chart.setPadding(new RectangleInsets(0, 0, 0, 0));
}

From source file:lisong_mechlab.view.graphs.DpsGraph.java

JFreeChart makechart() {
    JFreeChart chart = ChartFactory.createStackedXYAreaChart("Max DPS over range for " + loadout, "range [m]",
            "damage / second", getSeries(), PlotOrientation.VERTICAL, true, true, false);
    chart.getPlot().setDrawingSupplier(colours);

    chart.getLegend().setHorizontalAlignment(HorizontalAlignment.RIGHT);
    chart.getLegend().setVerticalAlignment(VerticalAlignment.TOP);

    LegendTitle legendTitle = chart.getLegend();
    XYTitleAnnotation titleAnnotation = new XYTitleAnnotation(0.98, 0.98, legendTitle,
            RectangleAnchor.TOP_RIGHT);/*  w  w w  .  j  ava 2 s . co m*/
    titleAnnotation.setMaxWidth(0.4);
    ((XYPlot) (chart.getPlot())).addAnnotation(titleAnnotation);
    chart.removeLegend();

    return chart;
}

From source file:de.uniol.ui.tsv.ui.LineChartDialog.java

/**
 * @return the resulting chart object/*from  w w  w. ja  v  a2 s  .  c  om*/
 */
protected JFreeChart createChart() {
    JFreeChart chart = ChartFactory.createTimeSeriesChartFast(title, xTitle, yTitle, xy, true, false, false);

    chart.setBackgroundPaint(Color.white);
    chart.getLegend().setBackgroundPaint(new Color(224, 224, 224));

    FastXYPlot plot = (FastXYPlot) chart.getPlot();
    //      plot.setBackgroundPaint(new Color(224, 224, 224));
    plot.setBackgroundPaint(new Color(77, 77, 77));
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    StandardXYItemRendererFast r = new StandardXYItemRendererFast(StandardXYItemRendererFast.LINES, null, null);
    plot.setRenderer(r);

    for (int i : seriesStrokes.keySet()) {
        r.setSeriesStroke(i, seriesStrokes.get(i));
    }
    for (int i : seriesColors.keySet()) {
        r.setSeriesPaint(i, seriesColors.get(i));
    }

    DateAxis da = new DateAxis(xTitle);
    if (useRelativeHourFormat) {
        da.setDateFormatOverride(new RelativeHourFormat());
    }
    da.setLowerMargin(0.03);
    plot.setDomainAxis(da);

    if (minRange != 0.0 && maxRange != 0.0) {
        ValueAxis yaxis = plot.getRangeAxis();
        yaxis.setRange(new Range(minRange, maxRange));
    }

    return chart;
}

From source file:org.infoglue.deliver.util.charts.TimeSeriesDiagram.java

/**
 * Creates a chart./* w  ww .  j ava  2s . com*/
 * 
 * @param dataset  a dataset.
 * 
 * @return A chart.
 */

private JFreeChart createChart(XYDataset dataset) {
    JFreeChart chart = ChartFactory.createTimeSeriesChart(header, axisXHeader, axisYHeader, dataset, true, true,
            false);

    chart.setBackgroundPaint(Color.white);

    LegendTitle legend = chart.getLegend();
    //legend.set .setDisplaySeriesShapes(true);

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

    XYItemRenderer renderer = plot.getRenderer();
    if (renderer instanceof StandardXYItemRenderer) {
        StandardXYItemRenderer rr = (StandardXYItemRenderer) renderer;
        //rr.setPlotShapes(true);
        rr.setShapesFilled(true);
    }

    DateAxis axis = (DateAxis) plot.getDomainAxis();

    if (this.timeGranulariry.equalsIgnoreCase("Week")) {
        DateTickUnit unit = new DateTickUnit(DateTickUnit.DAY, 7, new SimpleDateFormat(this.dateFormat));
        axis.setTickUnit(unit);
        axis.setTickMarkPosition(DateTickMarkPosition.START);

        axis.setDateFormatOverride(new SimpleDateFormat(this.dateFormat));
    } else {
        axis.setDateFormatOverride(new SimpleDateFormat(this.dateFormat));
    }
    /*
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat(this.dateFormat));
      */
    return chart;

}

From source file:GeMSE.Visualization.ElbowPlot.java

public void Plot(ArrayList<Double[]> pvData, ArrayList<Double[]> dData, int cut) {
    double maxY = 0;

    float[] secYColor = new float[3];
    Color.RGBtoHSB(153, 245, 255, secYColor);

    float[] priYColor = new float[3];
    Color.RGBtoHSB(255, 255, 255, priYColor);

    float[] cutColor = new float[3];
    Color.RGBtoHSB(255, 255, 0, cutColor);

    //create the series - add some dummy data
    XYSeries pvSeries = new XYSeries("Percentage of variance        ");
    for (int i = 1; i < pvData.size(); i++) {
        pvSeries.add(pvData.get(i)[0], pvData.get(i)[1]);
        maxY = Math.max(maxY, pvData.get(i)[1]);
    }//ww  w  .  j a  v a  2  s . c  o m

    XYSeries dSeries = new XYSeries("Percentage of differences between slopes        ");
    for (int i = 0; i < dData.size(); i++)
        dSeries.add(dData.get(i)[0], dData.get(i)[1]);

    XYSeries cutSeries = new XYSeries("Cut        ");
    cutSeries.add(cut, 0.0);
    cutSeries.add(cut, maxY);

    //create the datasets
    XYSeriesCollection pvDataSeries = new XYSeriesCollection();
    pvDataSeries.addSeries(pvSeries);

    XYSeriesCollection cutDataSeries = new XYSeriesCollection();
    cutDataSeries.addSeries(cutSeries);

    XYSeriesCollection dDataSeries = new XYSeriesCollection();
    dDataSeries.addSeries(dSeries);

    //construct the plot
    XYPlot plot = new XYPlot();
    plot.setDataset(0, pvDataSeries);
    plot.setDataset(1, cutDataSeries);
    plot.setDataset(2, dDataSeries);

    // use XYSplineRenderer if you want to smooth the lines.
    XYLineAndShapeRenderer pvRenderer = new XYLineAndShapeRenderer();
    pvRenderer.setSeriesPaint(0, Color.getHSBColor(priYColor[0], priYColor[1], priYColor[2]));

    BasicStroke dstroke = new BasicStroke(2.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1.0f,
            new float[] { 1.0f, 10.0f }, 0.0f);
    XYLineAndShapeRenderer dRenderer = new XYLineAndShapeRenderer();
    dRenderer.setSeriesPaint(0, Color.getHSBColor(secYColor[0], secYColor[1], secYColor[2]));
    dRenderer.setSeriesStroke(0, dstroke);

    BasicStroke cutStoke = new BasicStroke(4);
    // use XYSplineRenderer if you want to smooth the lines.
    //XYSplineRenderer cutRenderer = new XYSplineRenderer();
    XYLineAndShapeRenderer cutRenderer = new XYLineAndShapeRenderer();
    cutRenderer.setSeriesPaint(0, Color.getHSBColor(cutColor[0], cutColor[1], cutColor[2]));
    cutRenderer.setSeriesStroke(0, cutStoke);

    plot.setRenderer(0, pvRenderer);
    plot.setRenderer(1, cutRenderer);
    plot.setRenderer(2, dRenderer);

    plot.setRangeAxis(0, new NumberAxis("\n\nPercentage of Variance"));
    plot.setRangeAxis(1, new NumberAxis("Percentage of Difference Between Slopes"));
    plot.setDomainAxis(new NumberAxis("Number of Clusters\n\n"));

    //Map the data to the appropriate axis
    plot.mapDatasetToRangeAxis(0, 0);
    plot.mapDatasetToRangeAxis(1, 0);
    plot.mapDatasetToRangeAxis(2, 1);

    float[] hsbValues = new float[3];
    Color.RGBtoHSB(16, 23, 67, hsbValues);
    plot.setBackgroundPaint(Color.getHSBColor(hsbValues[0], hsbValues[1], hsbValues[2]));

    Font axisLabelFont = new Font("Dialog", Font.PLAIN, 14);
    Font axisTickLabelFont = new Font("Dialog", Font.PLAIN, 12);
    Font legendFont = new Font("Dialog", Font.PLAIN, 14);

    plot.setDomainGridlinePaint(Color.gray);
    plot.setRangeGridlinePaint(Color.gray);

    plot.getDomainAxis().setTickLabelPaint(Color.white);
    plot.getDomainAxis().setLabelPaint(Color.white);
    plot.getDomainAxis().setLabelFont(axisLabelFont);
    plot.getDomainAxis().setTickLabelFont(axisTickLabelFont);

    plot.getRangeAxis().setTickLabelPaint(Color.getHSBColor(priYColor[0], priYColor[1], priYColor[2]));
    plot.getRangeAxis().setLabelPaint(Color.getHSBColor(priYColor[0], priYColor[1], priYColor[2]));
    plot.getRangeAxis().setLabelFont(axisLabelFont);
    plot.getRangeAxis().setTickLabelFont(axisTickLabelFont);

    plot.getRangeAxis(1).setTickLabelPaint(Color.getHSBColor(secYColor[0], secYColor[1], secYColor[2]));
    plot.getRangeAxis(1).setLabelPaint(Color.getHSBColor(secYColor[0], secYColor[1], secYColor[2]));
    plot.getRangeAxis(1).setLabelFont(axisLabelFont);
    plot.getRangeAxis(1).setTickLabelFont(axisTickLabelFont);

    //generate the chart
    JFreeChart chart = new JFreeChart("\nSuggested number of clusters determined using Elbow method", getFont(),
            plot, true);

    chart.getTitle().setPaint(Color.white);
    chart.getLegend().setBackgroundPaint(Color.black);
    chart.getLegend().setItemPaint(Color.white);
    chart.getLegend().setPosition(RectangleEdge.BOTTOM);
    chart.getLegend().setItemFont(legendFont);

    float[] hsbValues2 = new float[3];
    Color.RGBtoHSB(36, 43, 87, hsbValues2);
    chart.setBackgroundPaint(Color.getHSBColor(hsbValues2[0], hsbValues2[1], hsbValues2[2]));
    JPanel chartPanel = new ChartPanel(chart);

    GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    chartPanel.setPreferredSize(
            new java.awt.Dimension((int) Math.round((gd.getDisplayMode().getWidth() * 1.5) / 3.0),
                    (int) Math.round((gd.getDisplayMode().getHeight() * 1.5) / 3.0)));

    setContentPane(chartPanel);
}

From source file:openqcm.ChartDynamicData.java

public ChartDynamicData() {

    // add primary axis frequency
    TimeSeries seriesFrequency = new TimeSeries("Frequency (Hz)");
    datasetFrequency = new TimeSeriesCollection(seriesFrequency);
    rangeAxisF = new NumberAxis("Frequency (Hz)");
    XYItemRenderer renderer = new StandardXYItemRenderer();
    renderer.setSeriesPaint(0, new Color(0, 142, 192));
    rangeAxisF.setAutoRangeIncludesZero(false);
    rangeAxisF.setAutoRange(true);//from   w  ww.  ja  v  a  2 s .  c o m
    rangeAxisF.setAutoRangeMinimumSize(50);

    plot.setDataset(0, datasetFrequency);
    plot.setRangeAxis(0, rangeAxisF);
    plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_LEFT);
    plot.setRenderer(0, renderer);
    plot.mapDatasetToRangeAxis(0, 0);

    // add secondary axis temperature
    TimeSeries seriesTemperature = new TimeSeries("Temperature (C)");
    datasetTemperature = new TimeSeriesCollection(seriesTemperature);
    plot.setDataset(1, datasetTemperature);
    NumberAxis rangeAxisT = new NumberAxis("Temperature (C)");
    rangeAxisT.setAutoRangeIncludesZero(false);
    rangeAxisT.setAutoRange(true);
    rangeAxisT.setAutoRangeMinimumSize(5);
    plot.setRangeAxis(1, rangeAxisT);
    plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT);
    // custom renderer for dinamically changing temperaure
    rendererT.setSeriesPaint(0, new Color(255, 128, 0));
    plot.setRenderer(1, rendererT);

    plot.mapDatasetToRangeAxis(1, 1);
    plotComb.add(plot);
    plotComb.setBackgroundPaint(Color.white);
    plotComb.setDomainGridlinePaint(Color.white);
    plotComb.setRangeGridlinePaint(Color.white);
    // enable panning for both axis
    plotComb.setRangePannable(true);
    plotComb.setDomainPannable(true);

    // set time axis properties
    // format time axis as hh:mm:ss
    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
    DateAxis axis = (DateAxis) plotComb.getDomainAxis();
    axis.setDateFormatOverride(format);
    // default auto range
    domainAxis.setAutoRange(true);

    // init the JFreeChart
    JFreeChart chart = new JFreeChart(plotComb);
    chart.setBorderPaint(Color.lightGray);
    chart.setBorderVisible(true);
    chart.setBackgroundPaint(Color.white);

    // set legend properties
    LegendTitle legend = chart.getLegend();
    legend.setPosition(RectangleEdge.TOP);
    legend.setItemFont(new Font("Dialog", Font.PLAIN, 9));

    // constructor for org.jfree.chart.ChartPanel
    // ChartPanel(JFreeChart chart, boolean properties, boolean save, boolean print, boolean zoom, boolean tooltips)
    ChartPanel chartPanel = new ChartPanel(chart, false, true, true, true, true);
    // enable mouse wheel support for the chart panel
    chartPanel.setMouseWheelEnabled(true);

    this.setLayout(new BorderLayout());
    // add real time chart to the frame
    this.add(chartPanel);
    this.validate();
}

From source file:dinamica.SyncChartOutput.java

public void print(GenericTransaction t) throws Throwable {

    //get chart parameters
    Recordset chartinfo = t.getRecordset("chartinfo");

    //get chart data
    String id = chartinfo.getString("data");
    Recordset data = (Recordset) getSession().getAttribute(id);
    if (data == null)
        throw new Throwable(
                "Invalid Recordset ID:" + id + " - The session does not contain an attribute with this ID.");

    //general chart params
    Integer width = (Integer) chartinfo.getValue("width");
    Integer height = (Integer) chartinfo.getValue("height");

    //load chart plugin
    String plugin = (String) chartinfo.getValue("chart-plugin");
    AbstractChartPlugin obj = (AbstractChartPlugin) Thread.currentThread().getContextClassLoader()
            .loadClass(plugin).newInstance();

    JFreeChart chart = null;
    synchronized (data) {
        chart = obj.getChart(chartinfo, data);
    }//from  ww w. java2 s.  co  m

    //set gradient
    chart.setBackgroundPaint(getGradient());

    //set border and legend params
    chart.setBorderPaint(Color.LIGHT_GRAY);
    chart.setBorderVisible(true);
    if (chart.getLegend() != null) {
        chart.getLegend().setBorder(0.2, 0.2, 0.2, 0.2);
        chart.getLegend().setPadding(5, 5, 5, 5);
        chart.getLegend().setMargin(4, 5, 4, 4);
    }

    //render chart in memory
    BufferedImage img = chart.createBufferedImage(width.intValue(), height.intValue());
    ByteArrayOutputStream b = new ByteArrayOutputStream(32768);

    //encode as PNG
    ImageIO.write(img, "png", b);

    //send bitmap via servlet output
    byte image[] = b.toByteArray();
    getResponse().setContentType("image/png");
    getResponse().setContentLength(image.length);
    OutputStream out = getResponse().getOutputStream();
    out.write(image);
    out.close();

    //save image bytes in session attribute if requested
    if (chartinfo.containsField("session")) {
        String session = chartinfo.getString("session");
        if (session != null && session.equals("true"))
            getSession().setAttribute(chartinfo.getString("image-id"), image);
    }

}

From source file:lisong_mechlab.view.graphs.SustainedDpsGraph.java

JFreeChart makechart() {
    JFreeChart chart = ChartFactory.createStackedXYAreaChart("Max Sustained DPS over range for " + loadout,
            "range [m]", "damage / second", getSeries(), PlotOrientation.VERTICAL, true, true, false);
    chart.getPlot().setDrawingSupplier(colours);

    chart.getLegend().setHorizontalAlignment(HorizontalAlignment.RIGHT);
    chart.getLegend().setVerticalAlignment(VerticalAlignment.TOP);

    LegendTitle legendTitle = chart.getLegend();
    XYTitleAnnotation titleAnnotation = new XYTitleAnnotation(0.98, 0.98, legendTitle,
            RectangleAnchor.TOP_RIGHT);/* w  w w  .  j av  a2s. co m*/
    titleAnnotation.setMaxWidth(0.4);
    ((XYPlot) (chart.getPlot())).addAnnotation(titleAnnotation);
    chart.removeLegend();

    return chart;
}

From source file:de.iteratec.iteraplan.presentation.dialog.GraphicalReporting.Line.JFreeChartLineGraphicCreator.java

/**
 * Creates the chart and applies some styling.
 * @return the JFreeChart wrapped in an iteratec API symbol.
 *///from ww  w.j  a  v  a2 s  .  c o  m
private JFreeChartSymbol createChart() {
    try {
        ChartFactory cf = new ChartFactory();
        cf.setTitle(title);
        cf.setxAxis(xAxis);
        cf.setyAxis(yAxis);
        JFreeChart chart = cf.createXYStepChart(dataset);
        LegendTitle legend = chart.getLegend();
        legend.setPosition(RectangleEdge.RIGHT);
        legend.setVisible(!emptyDataset); // don't show a legend, if the dataset is empty
        XYPlot xyplot = (XYPlot) chart.getPlot();
        xyplot.setBackgroundAlpha(0.4f);
        JFreeChartSymbol jfcs = new JFreeChartSymbol(chart);
        jfcs.setWidth(xResolution);
        jfcs.setHeight(yResolution);
        return jfcs;
    } catch (Exception e) {
        throw new IteraplanBusinessException(e);
    }
}

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

public void paintDeviationChart(Graphics graphics, int width, int height) {
    prepareData();/*from  w ww.j  ava  2  s. com*/

    JFreeChart chart = createChart(this.dataset);

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