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

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

Introduction

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

Prototype

public TextTitle(String text, Font font) 

Source Link

Document

Creates a new title, using default attributes where necessary.

Usage

From source file:com.android.ddmuilib.HeapPanel.java

/**
 * Creates the chart below the statistics table
 */// w ww .  j a v a 2 s. c o  m
private void createChart() {
    mAllocCountDataSet = new DefaultCategoryDataset();
    mChart = ChartFactory.createBarChart(null, "Size", "Count", mAllocCountDataSet, PlotOrientation.VERTICAL,
            false, true, false);

    // get the font to make a proper title. We need to convert the swt font,
    // into an awt font.
    Font f = mStatisticsBase.getFont();
    FontData[] fData = f.getFontData();

    // event though on Mac OS there could be more than one fontData, we'll only use
    // the first one.
    FontData firstFontData = fData[0];

    java.awt.Font awtFont = SWTUtils.toAwtFont(mStatisticsBase.getDisplay(), firstFontData,
            true /* ensureSameSize */);

    mChart.setTitle(new TextTitle("Allocation count per size", awtFont));

    Plot plot = mChart.getPlot();
    if (plot instanceof CategoryPlot) {
        // get the plot
        CategoryPlot categoryPlot = (CategoryPlot) plot;

        // set the domain axis to draw labels that are displayed even with many values.
        CategoryAxis domainAxis = categoryPlot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);

        CategoryItemRenderer renderer = categoryPlot.getRenderer();
        renderer.setBaseToolTipGenerator(new CategoryToolTipGenerator() {
            @Override
            public String generateToolTip(CategoryDataset dataset, int row, int column) {
                // get the key for the size of the allocation
                ByteLong columnKey = (ByteLong) dataset.getColumnKey(column);
                String rowKey = (String) dataset.getRowKey(row);
                Number value = dataset.getValue(rowKey, columnKey);

                return String.format("%1$d %2$s of %3$d bytes", value.intValue(), rowKey, columnKey.getValue());
            }
        });
    }
    mChartComposite = new ChartComposite(mStatisticsBase, SWT.BORDER, mChart, ChartComposite.DEFAULT_WIDTH,
            ChartComposite.DEFAULT_HEIGHT, ChartComposite.DEFAULT_MINIMUM_DRAW_WIDTH,
            ChartComposite.DEFAULT_MINIMUM_DRAW_HEIGHT, 3000, // max draw width. We don't want it to zoom, so we put a big number
            3000, // max draw height. We don't want it to zoom, so we put a big number
            true, // off-screen buffer
            true, // properties
            true, // save
            true, // print
            false, // zoom
            true); // tooltips

    mChartComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
}

From source file:org.yardstickframework.report.jfreechart.JFreeChartGraphPlotter.java

/**
 * @param folderToWrite Folder to write the resulted charts.
 * @param plots Collections of plots.//from  w  w w .jav a  2 s .com
 * @param infoMap Map with additional plot info.
 * @param mode Generation mode.
 * @throws Exception If failed.
 */
private static void processPlots(File folderToWrite, Collection<List<PlotData>> plots,
        Map<String, List<JFreeChartPlotInfo>> infoMap, JFreeChartGenerationMode mode) throws Exception {
    ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());

    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);

    int idx = -1;

    while (true) {
        idx++;

        DefaultXYDataset dataSet = new DefaultXYDataset();

        List<JFreeChartPlotInfo> infoList = new ArrayList<>();

        String xAxisLabel = "";
        String yAxisLabel = "";
        String plotName = "";

        int cnt = 0;

        for (List<PlotData> plotData0 : plots) {
            if (plotData0.size() <= idx)
                continue;

            PlotData plotData = plotData0.get(idx);

            dataSet.addSeries(plotData.plotName() + "_" + cnt++, plotData.series().data);

            xAxisLabel = plotData.xAxisLabel;
            yAxisLabel = plotData.yAxisLabel;
            plotName = plotData.plotName();

            infoList.add(info(plotData.series(), mode));
        }

        if (infoList.isEmpty())
            break;

        JFreeChart chart = ChartFactory.createXYLineChart("", xAxisLabel, yAxisLabel, dataSet,
                PlotOrientation.VERTICAL, false, false, false);

        AxisSpace as = new AxisSpace();

        as.add(150, RectangleEdge.LEFT);

        XYPlot plot = (XYPlot) chart.getPlot();

        BasicStroke stroke = new BasicStroke(1);

        plot.setRenderer(renderer);
        plot.setBackgroundPaint(WHITE);
        plot.setRangeGridlinePaint(GRAY);
        plot.setDomainGridlinePaint(GRAY);
        plot.setFixedRangeAxisSpace(as);
        plot.setOutlineStroke(stroke);

        for (int i = 0; i < infoList.size(); i++) {
            Color color = PLOT_COLORS[i % PLOT_COLORS.length];

            renderer.setSeriesPaint(i, color);
            renderer.setSeriesStroke(i, new BasicStroke(3)); // Line thickness.

            infoList.get(i).color(Integer.toHexString(color.getRGB()).substring(2));
        }

        ValueAxis axis = plot.getRangeAxis();

        Font font = new Font("Helvetica,Arial,sans-serif", Font.BOLD, axis.getTickLabelFont().getSize() + 5);

        axis.setTickLabelFont(font);
        axis.setLabelFont(font);
        plot.getDomainAxis().setTickLabelFont(font);
        plot.getDomainAxis().setLabelFont(font);

        chart.setTitle(new TextTitle(yAxisLabel, new Font(font.getName(), font.getStyle(), 30)));

        File res = new File(folderToWrite, plotName + ".png");

        ChartUtilities.saveChartAsPNG(res, chart, 1000, 500, info);

        infoMap.put(res.getAbsolutePath(), infoList);

        println("Chart is saved to file: ", res);
    }
}

From source file:edu.dlnu.liuwenpeng.ChartFactory.ChartFactory.java

/**    
* Creates a pie chart with default settings that compares 2 datasets.      
* The colour of each section will be determined by the move from the value    
* for the same key in <code>previousDataset</code>. ie if value1 > value2     
* then the section will be in green (unless <code>greenForIncrease</code>     
* is <code>false</code>, in which case it would be <code>red</code>).      
* Each section can have a shade of red or green as the difference can be     
* tailored between 0% (black) and percentDiffForMaxScale% (bright     
* red/green).    // w  w  w . j  a v  a 2 s .  c  om
* <p>    
* For instance if <code>percentDiffForMaxScale</code> is 10 (10%), a     
* difference of 5% will have a half shade of red/green, a difference of     
* 10% or more will have a maximum shade/brightness of red/green.    
* <P>    
* The chart object returned by this method uses a {@link PiePlot} instance    
* as the plot.    
* <p>    
* Written by <a href="mailto:opensource@objectlab.co.uk">Benoit     
* Xhenseval</a>.    
*    
* @param title  the chart title (<code>null</code> permitted).    
* @param dataset  the dataset for the chart (<code>null</code> permitted).    
* @param previousDataset  the dataset for the last run, this will be used     
*                         to compare each key in the dataset    
* @param percentDiffForMaxScale scale goes from bright red/green to black,    
*                               percentDiffForMaxScale indicate the change     
*                               required to reach top scale.    
* @param greenForIncrease  an increase since previousDataset will be     
*                          displayed in green (decrease red) if true.    
* @param legend  a flag specifying whether or not a legend is required.    
* @param tooltips  configure chart to generate tool tips?    
* @param urls  configure chart to generate URLs?    
* @param subTitle displays a subtitle with colour scheme if true    
* @param showDifference  create a new dataset that will show the %     
*                        difference between the two datasets.     
*    
* @return A pie chart.    
*/
public static JFreeChart createPieChart(String title, PieDataset dataset, PieDataset previousDataset,
        int percentDiffForMaxScale, boolean greenForIncrease, boolean legend, boolean tooltips, boolean urls,
        boolean subTitle, boolean showDifference) {

    PiePlot plot = new PiePlot(dataset);
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator());
    plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));

    if (tooltips) {
        plot.setToolTipGenerator(new StandardPieToolTipGenerator());
    }
    if (urls) {
        plot.setURLGenerator(new StandardPieURLGenerator());
    }

    List keys = dataset.getKeys();
    DefaultPieDataset series = null;
    if (showDifference) {
        series = new DefaultPieDataset();
    }

    double colorPerPercent = 255.0 / percentDiffForMaxScale;
    for (Iterator it = keys.iterator(); it.hasNext();) {
        Comparable key = (Comparable) it.next();
        Number newValue = dataset.getValue(key);
        Number oldValue = previousDataset.getValue(key);

        if (oldValue == null) {
            if (greenForIncrease) {
                plot.setSectionPaint(key, Color.green);
            } else {
                plot.setSectionPaint(key, Color.red);
            }
            if (showDifference) {
                series.setValue(key + " (+100%)", newValue);
            }
        } else {
            double percentChange = (newValue.doubleValue() / oldValue.doubleValue() - 1.0) * 100.0;
            double shade = (Math.abs(percentChange) >= percentDiffForMaxScale ? 255
                    : Math.abs(percentChange) * colorPerPercent);
            if (greenForIncrease && newValue.doubleValue() > oldValue.doubleValue()
                    || !greenForIncrease && newValue.doubleValue() < oldValue.doubleValue()) {
                plot.setSectionPaint(key, new Color(0, (int) shade, 0));
            } else {
                plot.setSectionPaint(key, new Color((int) shade, 0, 0));
            }
            if (showDifference) {
                series.setValue(
                        key + " (" + (percentChange >= 0 ? "+" : "")
                                + NumberFormat.getPercentInstance().format(percentChange / 100.0) + ")",
                        newValue);
            }
        }
    }

    if (showDifference) {
        plot.setDataset(series);
    }

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);

    if (subTitle) {
        TextTitle subtitle = null;
        subtitle = new TextTitle("Bright " + (greenForIncrease ? "red" : "green") + "=change >=-"
                + percentDiffForMaxScale + "%, Bright " + (!greenForIncrease ? "red" : "green") + "=change >=+"
                + percentDiffForMaxScale + "%", new Font("SansSerif", Font.PLAIN, 10));
        chart.addSubtitle(subtitle);
    }

    return chart;
}

From source file:com.rapidminer.gui.new_plotter.engine.jfreechart.JFreeChartPlotEngine.java

/**
 * Sets all the format options on the given chart like fonts, chart title, legend, legend
 * position etc.//w w w. j a  va 2 s. c  om
 */
private void formatChart(JFreeChart chart) {
    Plot plot = chart.getPlot();
    PlotConfiguration currentPlotConfigurationClone = plotInstance.getCurrentPlotConfigurationClone();

    // set plot background color
    plot.setBackgroundPaint(currentPlotConfigurationClone.getPlotBackgroundColor());

    formatLegend(chart);

    // set chart background color
    chart.setBackgroundPaint(currentPlotConfigurationClone.getChartBackgroundColor());

    // add title to chart
    String text = currentPlotConfigurationClone.getTitleText();
    if (text == null) {
        chart.setTitle(text);
    } else {
        Font font = currentPlotConfigurationClone.getTitleFont();
        if (font == null) {
            font = new Font("Dialog", Font.PLAIN, 10);
        }

        TextTitle textTitle = new TextTitle(text, font);
        textTitle.setPaint(currentPlotConfigurationClone.getTitleColor());

        chart.setTitle(textTitle);
    }
}

From source file:org.jfree.chart.demo.JFreeChartDemoBase.java

/**
 * Creates and returns a sample time series chart.
 *
 * @return a sample time series chart./*from  w  w w . ja  v a  2s .  c  o m*/
 */
public JFreeChart createTimeSeriesWithMAChart() {

    // create a default chart based on some sample data...
    final String title = this.resources.getString("timeseries.sample3.title");
    final String domain = this.resources.getString("timeseries.sample3.domain");
    final String range = this.resources.getString("timeseries.sample3.range");
    final String subtitleStr = this.resources.getString("timeseries.sample3.subtitle");
    final TimeSeries jpy = DemoDatasetFactory.createJPYTimeSeries();
    final TimeSeries mav = MovingAverage.createMovingAverage(jpy, "30 Day Moving Average", 30, 30);
    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    dataset.addSeries(jpy);
    dataset.addSeries(mav);
    final JFreeChart chart = ChartFactory.createTimeSeriesChart(title, domain, range, dataset, true, true,
            false);

    // then customise it a little...
    final TextTitle subtitle = new TextTitle(subtitleStr, new Font("SansSerif", Font.BOLD, 12));
    chart.addSubtitle(subtitle);
    chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 0, 1000, Color.blue));
    return chart;

}

From source file:probe.com.view.body.quantdatasetsoverview.quantproteinstabsheet.studies.ProteinStudyComparisonScatterPlotLayout.java

/**
 * Creates a sample jFreeChart.// w w w. ja  va 2  s  .  co m
 *
 * @param dataset the dataset.
 *
 * @return The jFreeChart.
 */
private void generateScatterplotchart(DiseaseGroupsComparisonsProteinLayout cp, int w, int h) {

    final XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries downSer = new XYSeries(0);
    XYSeries stableSer = new XYSeries(1);
    XYSeries upSer = new XYSeries(2);

    XYSeries novalueProvidedSer = new XYSeries(3);

    XYSeries downSerII = new XYSeries(4);
    XYSeries stableSerII = new XYSeries(5);
    XYSeries upSerII = new XYSeries(6);
    XYSeries novalueProvidedSerII = new XYSeries(7);

    //        XYSeries plusSeries = new XYSeries(6);
    double downCounter = 1;
    double stableCounter = 3;
    double upCounter = 5;
    double novalueProvidedCounter = 3;

    patientGroupsNumToDsIdMap.clear();

    final Map<Integer, int[]> paTGrNumbtrendMap = new HashMap<Integer, int[]>();
    double maxPatNumber = -1.0;
    for (String protTrend : cp.getPatientsNumToTrindMap().keySet()) {
        List<Integer> patNums = cp.getPatientsNumToTrindMap().get(protTrend);
        int coun = 0;
        for (int i : patNums) {
            if (i > maxPatNumber) {
                maxPatNumber = i;
            }
            if (!patientGroupsNumToDsIdMap.containsKey(i)) {
                ComparisonDetailsBean pGr = new ComparisonDetailsBean();
                patientGroupsNumToDsIdMap.put(i, pGr);

            }
            if (!paTGrNumbtrendMap.containsKey(i)) {
                int[] values = new int[4];
                paTGrNumbtrendMap.put(i, values);
            }

            int[] values = paTGrNumbtrendMap.get(i);
            ComparisonDetailsBean pGr = patientGroupsNumToDsIdMap.get(i);
            if (protTrend.equalsIgnoreCase("noValueProvided")) {
                values[3] = values[3] + 1;
                pGr.addNovalueProvided(cp.getDSID(3, coun));

            } else if (protTrend.equalsIgnoreCase("up")) {
                values[2] = values[2] + 1;

                pGr.addUpRegulated(cp.getDSID(0, coun));

            } else if (protTrend.equalsIgnoreCase("down")) {
                values[0] = values[0] + 1;
                pGr.addDownRegulated(cp.getDSID(2, coun));
            } else {
                values[1] = values[1] + 1;
                pGr.addNotRegulated(cp.getDSID(1, coun));
            }
            paTGrNumbtrendMap.put(i, values);
            patientGroupsNumToDsIdMap.put(i, pGr);
            coun++;
        }

    }

    for (int i : paTGrNumbtrendMap.keySet()) {
        int[] values = paTGrNumbtrendMap.get(i);
        if ((values[2] > 1)) {
            upSer.add(upCounter, i);
            upSerII.add(upCounter, i);
        } else if ((values[2] == 1)) {
            upSer.add(upCounter, i);
        }
        if ((values[1] == 1)) {
            stableSer.add(stableCounter, i);
        } else if ((values[1] > 1)) {
            stableSer.add(stableCounter, i);
            stableSerII.add(stableCounter, i);
        }

        if ((values[0] > 1)) {
            downSer.add(downCounter, i);
            downSerII.add(downCounter, i);
        } else if ((values[0] == 1)) {
            downSer.add(downCounter, i);
        }
        if ((values[3] == 1)) {
            novalueProvidedSer.add(novalueProvidedCounter, i);
        } else if ((values[3] > 1)) {
            novalueProvidedSer.add(stableCounter, i);
            novalueProvidedSerII.add(stableCounter, i);
        }

    }

    dataset.addSeries(downSer);
    dataset.addSeries(stableSer);
    dataset.addSeries(upSer);
    dataset.addSeries(novalueProvidedSer);
    dataset.addSeries(downSerII);
    dataset.addSeries(stableSerII);
    dataset.addSeries(upSerII);
    dataset.addSeries(novalueProvidedSerII);
    //        if((downSerII.getItemCount()+stableSerII.getItemCount()+upSerII.getItemCount()+downSer.getItemCount()+stableSer.getItemCount()+upSer.getItemCount())==0)
    //            return;
    //        dataset.addSeries(plusSeries);
    final String[] labels = new String[] { " ", ("Decreased (" + cp.getSignificantDown() + ")"), " ",
            ("Equal (" + cp.getStable() + ")"), " ", ("Increased (" + cp.getSignificantUp() + ")"), "" };
    final Color[] labelsColor = new Color[] { Color.LIGHT_GRAY, new Color(80, 183, 71), Color.LIGHT_GRAY,
            new Color(1, 141, 244), Color.LIGHT_GRAY, Color.RED, Color.LIGHT_GRAY };
    final SymbolAxis domainAxis = new SymbolAxis("X", labels) {

        @Override
        protected void drawGridBandsVertical(Graphics2D g2, Rectangle2D drawArea, Rectangle2D plotArea,
                boolean firstGridBandIsDark, List ticks) {
            List udatedTicksList = new ArrayList();

            for (Object tick : ticks) {
                if (tick.toString().equalsIgnoreCase(labels[custTrend + 1])) {
                    udatedTicksList.add(tick);
                }
            }
            //                System.out.println("at ticks is "+ticks);
            //                 System.out.println("at udatedTicksList is "+udatedTicksList);
            //                int factor = (int) ((plotArea.getHeight() / 5) * 0.25);
            //
            //                Rectangle2D up = new Rectangle((int) drawArea.getX(), (int) drawArea.getY() - factor, (int) drawArea.getWidth(), (int) drawArea.getHeight());
            //                Rectangle2D pa = new Rectangle((int) plotArea.getX(), (int) plotArea.getY() - factor, (int) plotArea.getWidth(), (int) plotArea.getHeight());

            super.drawGridBandsVertical(g2, drawArea, plotArea, firstGridBandIsDark, udatedTicksList); //To change body of generated methods, choose Tools | Templates.
        }

        int x = 0;

        @Override
        public Paint getTickLabelPaint() {
            if (x >= labels.length) {
                x = 0;
            }
            return labelsColor[x++];
        }

    };
    domainAxis.setAutoRangeIncludesZero(false);
    Font f = new Font("Verdana", Font.PLAIN, 11);
    domainAxis.setTickLabelFont(f);
    domainAxis.setAutoRange(false);
    domainAxis.setLabel(null);

    //        domainAxis.setGridBandsVisible(false);
    String xTile = "#Patients";

    JFreeChart jFreeChart = ChartFactory.createScatterPlot(null, null, // domain axis label
            null, // range axis label
            dataset, // data
            PlotOrientation.HORIZONTAL, // orientation
            false, // include legend
            false, // tooltips?
            false // URLs?
    );
    XYPlot plot1 = (XYPlot) jFreeChart.getPlot();
    XYPlot xyplot = new XYPlot(dataset, plot1.getDomainAxis(), plot1.getRangeAxis(), plot1.getRenderer()) {

        @Override
        public void drawDomainTickBands(Graphics2D g2, Rectangle2D dataArea, List ticks) {

            if (custTrend == -1) {
                super.drawDomainTickBands(g2, dataArea, ticks);
                return;

            }
            List udatedTicksList = new ArrayList();
            for (Object tick : ticks) {
                if (tick.toString().equalsIgnoreCase(labels[custTrend + 1])) {
                    udatedTicksList.add(tick);
                }
            }
            Rectangle2D up;
            int factor = (int) ((dataArea.getHeight() / 5) * 0.5);
            if (custTrend == 4) {
                up = new Rectangle((int) dataArea.getX(), (int) dataArea.getY() + factor,
                        (int) dataArea.getWidth(), (int) dataArea.getHeight());

            } else if (custTrend == 2) {
                up = new Rectangle((int) dataArea.getX(), (int) dataArea.getY() - factor,
                        (int) dataArea.getWidth(), (int) dataArea.getHeight());

            } else {
                up = new Rectangle((int) dataArea.getX(), (int) dataArea.getY() - factor,
                        (int) dataArea.getWidth(), (int) dataArea.getHeight());
            }

            super.drawDomainTickBands(g2, up, udatedTicksList); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        protected void drawDomainGridlines(Graphics2D g2, Rectangle2D dataArea, List ticks) {
            super.drawDomainGridlines(g2, dataArea, ticks); //To change body of generated methods, choose Tools | Templates.
        }

        private int x = 0;

        @Override
        public Paint getDomainGridlinePaint() {
            if (x >= labels.length) {
                x = 0;
            }
            if (x == 1 || x == 3 || x == 5) {
                x++;
                return Color.WHITE;
            } else {
                x++;
                return super.getDomainGridlinePaint(); //To change body of generated methods, choose Tools | Templates.
            }
        }
    };
    if (custTrend != -1) {
        domainAxis.setGridBandsVisible(true);
        if (custTrend == 4) {
            domainAxis.setGridBandPaint(Color.decode("#ffe5e5"));
            xyplot.setDomainTickBandPaint(Color.decode("#ffe5e5"));
            domainAxis.setGridBandAlternatePaint(Color.decode("#ffe5e5"));
        } else if (custTrend == 0) {
            domainAxis.setGridBandPaint(Color.decode("#e5ffe5"));
            xyplot.setDomainTickBandPaint(Color.white);
        } else if (custTrend == 2) {
            domainAxis.setGridBandPaint(Color.decode("#e6f4ff"));
            xyplot.setDomainTickBandPaint(Color.white);
        }

    } else {
        domainAxis.setGridBandsVisible(false);
    }
    xyplot.setOrientation(PlotOrientation.HORIZONTAL);
    JFreeChart tempScatterPlot = new JFreeChart(xyplot);
    tempScatterPlot.setBackgroundPaint(Color.WHITE);
    tempScatterPlot.getLegend().setVisible(false);
    Color c = new Color(242, 242, 242);
    xyplot.setDomainAxis(domainAxis);
    xyplot.setDomainGridlinePaint(Color.GRAY);
    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.GRAY);
    xyplot.setOutlinePaint(Color.GRAY);
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) xyplot.getRenderer();
    ValueAxis va = xyplot.getDomainAxis();
    va.setAutoRange(false);
    va.setMinorTickCount(0);
    va.setVisible(true);
    maxPatNumber = Math.ceil(maxPatNumber / 100.0) * 100;
    xyplot.getRangeAxis().setRange(0, maxPatNumber);
    NumberAxis rangeAxis = (NumberAxis) xyplot.getRangeAxis();
    rangeAxis.setTickUnit(new NumberTickUnit(10));
    rangeAxis.setLabel(xTile);
    rangeAxis.setLabelFont(f);
    rangeAxis.setLabelPaint(Color.GRAY);

    va.setRange(0, 6);
    xyplot.setBackgroundPaint(Color.WHITE);
    renderer.setUseOutlinePaint(true);

    Color c0 = new Color(80, 183, 71);
    renderer.setSeriesPaint(0, c0);
    renderer.setSeriesOutlinePaint(0, Color.WHITE);

    Color c1 = new Color(1, 141, 244);
    renderer.setSeriesPaint(1, c1);
    renderer.setSeriesOutlinePaint(1, Color.WHITE);

    Color c2 = new Color(204, 0, 0);
    renderer.setSeriesPaint(2, c2);
    renderer.setSeriesOutlinePaint(2, Color.WHITE);

    renderer.setSeriesPaint(3, Color.decode("#b5babb"));
    renderer.setSeriesOutlinePaint(3, Color.WHITE);

    renderer.setSeriesPaint(4, new Color(150, 212, 145));
    renderer.setSeriesOutlinePaint(4, new Color(150, 212, 145));

    renderer.setSeriesPaint(5, new Color(103, 187, 248));
    renderer.setSeriesOutlinePaint(5, new Color(103, 187, 248));

    renderer.setSeriesPaint(6, new Color(224, 102, 102));
    renderer.setSeriesOutlinePaint(6, new Color(224, 102, 102));

    renderer.setSeriesPaint(7, Color.decode("#b5babb"));
    renderer.setSeriesOutlinePaint(7, Color.GRAY);

    //        renderer.setSeriesPaint(6, Color.BLACK);
    //        renderer.setSeriesOutlinePaint(6, Color.BLACK);
    Shape downArr = ShapeUtilities.createDownTriangle(7f);
    Shape notRShape = ShapeUtilities.createDiamond(7f);
    Shape upArr = ShapeUtilities.createUpTriangle(7);

    Shape downArrII = ShapeUtilities.createTranslatedShape(ShapeUtilities.createDownTriangle(6f), 5, -5);
    Shape notRShapeII = ShapeUtilities.createTranslatedShape(ShapeUtilities.createDiamond(6f), 0, -7);
    Shape upArrII = ShapeUtilities.createTranslatedShape(ShapeUtilities.createUpTriangle(6f), 4, -4);

    //        Shape plus = ShapeUtilities.createTranslatedShape(ShapeUtilities.createRegularCross(3f, 0.4f), 11, -7);
    renderer.setSeriesShape(0, downArr);
    renderer.setSeriesShape(1, notRShape);
    renderer.setSeriesShape(2, upArr);

    renderer.setSeriesShape(3, notRShape);

    renderer.setSeriesShape(4, downArrII);
    renderer.setSeriesShape(5, notRShapeII);
    renderer.setSeriesShape(6, upArrII);

    renderer.setSeriesShape(7, notRShapeII);
    //       renderer.setSeriesShape(6, plus);

    renderer.setBaseItemLabelsVisible(true);
    renderer.setBaseItemLabelGenerator(new SymbolicXYItemLabelGenerator() {
        private final int[] indexer = new int[] { 0, 1, 2, 3, 0, 1, 2, 3 };

        @Override
        public String generateLabel(XYDataset dataset, int series, int category) {
            if (series > 3) {
                int patNumber = (int) dataset.getYValue(series, category);
                //                    int trend = (int) dataset.getXValue(series, category);
                if (series == 7 || series == 5) {
                    return "\t  " + paTGrNumbtrendMap.get(patNumber)[indexer[series]];
                } else {
                    return "\t   " + paTGrNumbtrendMap.get(patNumber)[indexer[series]];
                }

            }

            return ""; //To change body of generated methods, choose Tools | Templates.
        }

    });
    ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT,
            TextAnchor.TOP_LEFT, 0.0);

    renderer.setSeriesPositiveItemLabelPosition(4, position);
    renderer.setSeriesPositiveItemLabelPosition(5, position);
    renderer.setSeriesPositiveItemLabelPosition(6, position);
    renderer.setSeriesPositiveItemLabelPosition(7, position);

    renderer.setBaseItemLabelFont(f);

    tempScatterPlot.setBorderVisible(false);

    xyplot.setSeriesRenderingOrder(SeriesRenderingOrder.REVERSE);

    heighlightedScatterPlottImgUrl = saveToFile(tempScatterPlot, w, h, defaultScatterPlotRenderingInfo);

    xyplot.setBackgroundPaint(Color.WHITE);
    defaultScatterPlottImgUrl = saveToFile(tempScatterPlot, w, h, defaultScatterPlotRenderingInfo);

    //        xyplot.setBackgroundPaint(c);

    if (custTrend != -1) {
        domainAxis.setGridBandsVisible(true);
        if (custTrend == 4) {
            domainAxis.setGridBandPaint(Color.decode("#ffe5e5"));
            xyplot.setDomainTickBandPaint(Color.decode("#ffe5e5"));
            domainAxis.setGridBandAlternatePaint(Color.decode("#ffe5e5"));
        } else if (custTrend == 0) {
            domainAxis.setGridBandPaint(Color.decode("#e5ffe5"));
            xyplot.setDomainTickBandPaint(c);
        } else if (custTrend == 2) {
            domainAxis.setGridBandPaint(Color.decode("#e6f4ff"));
            xyplot.setDomainTickBandPaint(c);
        }

    }

    String textTitle = comparisonTitle.getValue().split("bold;'>")[1].replace("</font>", "");
    TextTitle title = new TextTitle(textTitle, f);

    scatterPlot = new JFreeChart(xyplot);
    scatterPlot.setTitle(title);

    scatterPlot.setBorderVisible(false);
    scatterPlot.setBackgroundPaint(Color.WHITE);
    scatterPlot.getLegend().setVisible(false);
    dsKeyDatasetMap.clear();
    for (int i = 0; i < defaultScatterPlotRenderingInfo.getEntityCollection().getEntityCount(); i++) {
        final ChartEntity entity = defaultScatterPlotRenderingInfo.getEntityCollection().getEntity(i);
        if (entity instanceof XYItemEntity) {

            int x = ((XYItemEntity) entity).getSeriesIndex();
            int y = ((XYItemEntity) entity).getItem();

            if (((XYItemEntity) entity).getDataset().getYValue(x,
                    y) > (int) ((XYItemEntity) entity).getDataset().getYValue(x, y)) {
                continue;
            }
            if (((XYItemEntity) entity).getSeriesIndex() > 3) {

                continue;
            }

            String[] arr = ((XYItemEntity) entity).getShapeCoords().split(",");
            int xSer = Integer.valueOf(arr[0]);
            int ySer = Integer.valueOf(arr[1]);
            int ySerEnd = Integer.valueOf(arr[3]);
            int patGrNumber = (int) ((XYItemEntity) entity).getDataset().getYValue(x, y);
            int trend = Integer.valueOf(((XYItemEntity) entity).getDataset()
                    .getSeriesKey(((XYItemEntity) entity).getSeriesIndex()).toString());

            ComparisonDetailsBean cpDetails = patientGroupsNumToDsIdMap.get(patGrNumber);
            List<Integer> dsList = cpDetails.getRegulatedList(trend);
            StringBuilder sb = new StringBuilder();

            for (int dsId : dsList) {
                QuantDatasetObject ds;

                sb.append("<h4>").append((Quant_Central_Manager.getFullQuantDatasetMap().get(dsId)).getAuthor())
                        .append(" ")
                        .append((Quant_Central_Manager.getFullQuantDatasetMap().get(dsId)).getYear())
                        .append("<h4/>");
                sb.append("<p></p>");
                ds = Quant_Central_Manager.getFullQuantDatasetMap().get(dsId);

                dsKeyDatasetMap.put("_-_" + dsId + "_-_" + comparisonProtein.getProteinAccssionNumber() + "_-_",
                        ds);
            }
            String tooltip = sb.toString().substring(0, sb.toString().length() - 7);
            SquaredDot square = new SquaredDot("squared");
            if (paTGrNumbtrendMap.get(patGrNumber)[trend] > 1) {
                square.setWidth(20 + "px");
                square.setHeight(15 + "px");
            } else {
                square.setWidth(10 + "px");
                square.setHeight(10 + "px");
            }
            square.setDescription(tooltip);
            square.setParam("trend", trend);
            square.setParam("pGrNumber", patGrNumber);
            int top = (ySer - 4);
            if (ySer > ySerEnd) {
                top = ySerEnd - 3;
            }
            defaultChartLayout.addComponent(square, "left: " + (xSer - 5) + "px; top: " + top + "px;");
        }
    }

}

From source file:org.jfree.chart.demo.JFreeChartDemoBase.java

/**
 * Displays a vertical bar chart in its own frame.
 *
 * @return a high low chart.//w  w w. j av  a  2  s  . c o  m
 */
public JFreeChart createHighLowChart() {

    // create a default chart based on some sample data...
    final String title = this.resources.getString("timeseries.highlow.title");
    final String domain = this.resources.getString("timeseries.highlow.domain");
    final String range = this.resources.getString("timeseries.highlow.range");
    final String subtitleStr = this.resources.getString("timeseries.highlow.subtitle");
    final DefaultHighLowDataset data = DemoDatasetFactory.createHighLowDataset();
    final JFreeChart chart = ChartFactory.createHighLowChart(title, domain, range, data, true);

    // then customise it a little...
    final TextTitle subtitle = new TextTitle(subtitleStr, new Font("SansSerif", Font.BOLD, 12));
    chart.addSubtitle(subtitle);
    chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 0, 1000, Color.magenta));
    return chart;

}

From source file:KIDLYFactory.java

/**
 * Creates a pie chart with default settings that compares 2 datasets.
 * The colour of each section will be determined by the move from the value
 * for the same key in <code>previousDataset</code>. ie if value1 > value2
 * then the section will be in green (unless <code>greenForIncrease</code>
 * is <code>false</code>, in which case it would be <code>red</code>).
 * Each section can have a shade of red or green as the difference can be
 * tailored between 0% (black) and percentDiffForMaxScale% (bright
 * red/green).// w  w w . j  ava 2s .c  om
 * <p>
 * For instance if <code>percentDiffForMaxScale</code> is 10 (10%), a
 * difference of 5% will have a half shade of red/green, a difference of
 * 10% or more will have a maximum shade/brightness of red/green.
 * <P>
 * The chart object returned by this method uses a {@link PiePlot} instance
 * as the plot.
 * <p>
 * Written by <a href="mailto:opensource@objectlab.co.uk">Benoit
 * Xhenseval</a>.
 *
 * @param title  the chart title (<code>null</code> permitted).
 * @param dataset  the dataset for the chart (<code>null</code> permitted).
 * @param previousDataset  the dataset for the last run, this will be used
 *                         to compare each key in the dataset
 * @param percentDiffForMaxScale scale goes from bright red/green to black,
 *                               percentDiffForMaxScale indicate the change
 *                               required to reach top scale.
 * @param greenForIncrease  an increase since previousDataset will be
 *                          displayed in green (decrease red) if true.
 * @param legend  a flag specifying whether or not a legend is required.
 * @param tooltips  configure chart to generate tool tips?
 * @param urls  configure chart to generate URLs?
 * @param subTitle displays a subtitle with colour scheme if true
 * @param showDifference  create a new dataset that will show the %
 *                        difference between the two datasets.
 *
 * @return A pie chart.
 */
public static JFreeChart createPieChart(String title, PieDataset dataset, PieDataset previousDataset,
        int percentDiffForMaxScale, boolean greenForIncrease, boolean legend, boolean tooltips, boolean urls,
        boolean subTitle, boolean showDifference) {

    PiePlot plot = new PiePlot(dataset);
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator());
    plot.setInsets(new RectangleInsets(0.0, 5.0, 5.0, 5.0));

    if (tooltips) {
        plot.setToolTipGenerator(new StandardPieToolTipGenerator());
    }
    if (urls) {
        plot.setURLGenerator(new StandardPieURLGenerator());
    }

    List keys = dataset.getKeys();
    DefaultPieDataset series = null;
    if (showDifference) {
        series = new DefaultPieDataset();
    }

    double colorPerPercent = 255.0 / percentDiffForMaxScale;
    for (Iterator it = keys.iterator(); it.hasNext();) {
        Comparable key = (Comparable) it.next();
        Number newValue = dataset.getValue(key);
        Number oldValue = previousDataset.getValue(key);

        if (oldValue == null) {
            if (greenForIncrease) {
                plot.setSectionPaint(key, Color.green);
            } else {
                plot.setSectionPaint(key, Color.red);
            }
            if (showDifference) {
                series.setValue(key + " (+100%)", newValue);
            }
        } else {
            double percentChange = (newValue.doubleValue() / oldValue.doubleValue() - 1.0) * 100.0;
            double shade = (Math.abs(percentChange) >= percentDiffForMaxScale ? 255
                    : Math.abs(percentChange) * colorPerPercent);
            if (greenForIncrease && newValue.doubleValue() > oldValue.doubleValue()
                    || !greenForIncrease && newValue.doubleValue() < oldValue.doubleValue()) {
                plot.setSectionPaint(key, new Color(0, (int) shade, 0));
            } else {
                plot.setSectionPaint(key, new Color((int) shade, 0, 0));
            }
            if (showDifference) {
                series.setValue(
                        key + " (" + (percentChange >= 0 ? "+" : "")
                                + NumberFormat.getPercentInstance().format(percentChange / 100.0) + ")",
                        newValue);
            }
        }
    }

    if (showDifference) {
        plot.setDataset(series);
    }

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);

    if (subTitle) {
        TextTitle subtitle = null;
        subtitle = new TextTitle("Bright " + (greenForIncrease ? "red" : "green") + "=change >=-"
                + percentDiffForMaxScale + "%, Bright " + (!greenForIncrease ? "red" : "green") + "=change >=+"
                + percentDiffForMaxScale + "%", new Font("SansSerif", Font.PLAIN, 10));
        chart.addSubtitle(subtitle);
    }
    currentTheme.apply(chart);
    return chart;
}

From source file:org.hxzon.demo.jfreechart.CategoryDatasetDemo2.java

private static JFreeChart createMultiplePieChart3D(CategoryDataset dataset) {

    MultiplePiePlot plot = new MultiplePiePlot(dataset);
    plot.setDataExtractOrder(TableOrder.BY_COLUMN);
    plot.setBackgroundPaint(null);/*from  w  ww  .j ava2 s  .  c  o m*/
    plot.setOutlineStroke(null);

    JFreeChart pieChart = new JFreeChart(new PiePlot3D(null));
    TextTitle seriesTitle = new TextTitle("Series Title", new Font("SansSerif", Font.BOLD, 12));
    seriesTitle.setPosition(RectangleEdge.BOTTOM);
    pieChart.setTitle(seriesTitle);
    pieChart.removeLegend();
    pieChart.setBackgroundPaint(null);
    plot.setPieChart(pieChart);

    if (tooltips) {
        PieToolTipGenerator tooltipGenerator = new StandardPieToolTipGenerator();
        PiePlot pp = (PiePlot) plot.getPieChart().getPlot();
        pp.setToolTipGenerator(tooltipGenerator);
    }

    if (urls) {
        PieURLGenerator urlGenerator = new StandardPieURLGenerator();
        PiePlot pp = (PiePlot) plot.getPieChart().getPlot();
        pp.setURLGenerator(urlGenerator);
    }

    JFreeChart chart = new JFreeChart("MultiplePie Chart 3D Demo 1", JFreeChart.DEFAULT_TITLE_FONT, plot,
            legend);
    chart.setBackgroundPaint(Color.white);

    PiePlot piePlot = (PiePlot) pieChart.getPlot();

    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));
    piePlot.setSectionPaint("First", gp0);
    piePlot.setSectionPaint("Second", gp1);
    piePlot.setSectionPaint("Third", gp2);

    return chart;

}

From source file:skoa.helpers.Graficos.java

private void barrasDual2() {
    unificarDatosFicheros();//from w  ww  .  jav a 2  s .  c o  m
    Vector<String> vectorOrdenUnidades = new Vector<String>();
    vectorOrdenUnidades = ordenDeUnidades();
    aplicarDiferencia(vectorOrdenUnidades);
    //En este caso, que queremos 2 ejes, MARCAMOS LA DIFERENCIA AL RECOGER EL 2 DATASET.
    CategoryDataset dataset = obtenerSerieBarrasDual(1);
    //String unidad=vectorOrdenUnidades.elementAt(0);
    String unidad;
    if (vectorOrdenUnidades.elementAt(0).indexOf("W") >= 0 || vectorOrdenUnidades.elementAt(0).indexOf("L") >= 0
            || vectorOrdenUnidades.elementAt(0).indexOf("m") >= 0
            || vectorOrdenUnidades.elementAt(0).indexOf("B") >= 0)
        unidad = vectorOrdenUnidades.elementAt(0);
    else if (vectorOrdenUnidades.elementAt(0).indexOf("C") >= 0)
        unidad = "C";
    else
        unidad = "";
    final CategoryAxis domainAxis = new CategoryAxis("Fechas");
    final NumberAxis rangeAxis = new NumberAxis("Mediciones (" + unidad + ")");
    final BarRenderer renderer1 = new BarRenderer();
    final CategoryPlot plot = new CategoryPlot(dataset, domainAxis, rangeAxis, renderer1) {
        private static final long serialVersionUID = 1L;

        //ESPECIAL. Modificamos la leyenda, para que se vea correcta, cogiendo los 2 items deseados.
        public LegendItemCollection getLegendItems() {
            final LegendItemCollection result = new LegendItemCollection();
            final CategoryDataset data = getDataset();
            if (data != null) {
                final CategoryItemRenderer r = getRenderer();
                if (r != null) {
                    final LegendItem item;
                    try { //Se recoge la excepcion en caso de haber solo
                        item = r.getLegendItem(0, 0); //una lnea en el fichero unificado, porque
                    } catch (Exception e) { //no habria nada en diferenciaAplicada.
                        System.out.println("MAL " + e);
                        return null;
                    }
                    result.add(item);
                }
            }
            final CategoryDataset dset2 = getDataset(1);
            if (dset2 != null) {
                final CategoryItemRenderer renderer2 = getRenderer(1);
                if (renderer2 != null) {
                    final LegendItem item = renderer2.getLegendItem(1, 1);
                    result.add(item);
                }
            }
            return result;
        }
    };
    final JFreeChart grafica = new JFreeChart("Valores medidos de las direcciones de grupo", plot);
    plot.setBackgroundPaint(new Color(0xEE, 0xEE, 0xFF));
    plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
    CategoryDataset dataset2 = obtenerSerieBarrasDual(2);
    //unidad=vectorOrdenUnidades.elementAt(1);
    if (vectorOrdenUnidades.elementAt(1).indexOf("W") >= 0 || vectorOrdenUnidades.elementAt(1).indexOf("L") >= 0
            || vectorOrdenUnidades.elementAt(1).indexOf("m") >= 0
            || vectorOrdenUnidades.elementAt(1).indexOf("B") >= 0)
        unidad = vectorOrdenUnidades.elementAt(1);
    else if (vectorOrdenUnidades.elementAt(1).indexOf("C") >= 0)
        unidad = "C";
    else
        unidad = "";
    plot.setDataset(1, dataset2);
    plot.mapDatasetToRangeAxis(1, 1);
    final ValueAxis axis2 = new NumberAxis("Mediciones (" + unidad + ")");
    plot.setRangeAxis(1, axis2);
    plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_RIGHT);
    final BarRenderer renderer2 = new BarRenderer();
    renderer2.setShadowVisible(false); //Esconder las sombras de la barra 1.
    plot.setRenderer(1, renderer2);
    BarRenderer renderer = new BarRenderer();
    renderer.setShadowVisible(false); //Esconder las sombras de la barra 2.
    plot.setRenderer(0, renderer);
    plot.setRangeGridlinePaint(Color.BLACK); //Color de las lineas divisorias.
    //Subttulos
    if (fechaInicial.isEmpty()) {
        fechaInicial = fechaFinal = "?";
    }
    TextTitle t = new TextTitle("desde " + fechaInicial + " hasta " + fechaFinal,
            new Font("SanSerif", Font.ITALIC, 12));
    grafica.addSubtitle(t);
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
    domainAxis.setTickLabelFont(new Font("Dialog", Font.PLAIN, 8)); //Letra de las fechas ms pequea
    grafica.setBackgroundPaint(Color.white);
    //-------------------------------------------------
    //Guarda la imagen:
    BufferedImage i1 = grafica.createBufferedImage(400, 300);
    BufferedImage i2 = grafica.createBufferedImage(900, 600);
    BufferedImage imag1 = convertirTipo(i1, BufferedImage.TYPE_INT_RGB);//!OBLIGATORIO!Para que al guardar la imagen,
    BufferedImage imag2 = convertirTipo(i2, BufferedImage.TYPE_INT_RGB);//no se vea transparente naranja.
    try {
        ImageIO.write(imag1, "jpg", new File(ruta + "BarrasSmall.jpg"));
        ImageIO.write(imag2, "jpg", new File(ruta + "BarrasBig.jpg"));
    } catch (IOException e) {
        System.out.println("Error de escritura");
    }
}