Example usage for org.jfree.chart.plot PiePlot setSectionPaint

List of usage examples for org.jfree.chart.plot PiePlot setSectionPaint

Introduction

In this page you can find the example usage for org.jfree.chart.plot PiePlot setSectionPaint.

Prototype

public void setSectionPaint(int section, Paint paint) 

Source Link

Document

Sets the paint used to fill a section of the pie and sends a PlotChangeEvent to all registered listeners.

Usage

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

protected void configureChart(final JFreeChart chart) {
    super.configureChart(chart);

    final Plot plot = chart.getPlot();
    final MultiplePiePlot mpp = (MultiplePiePlot) plot;
    final JFreeChart pc = mpp.getPieChart();
    configureSubChart(pc);//from   ww w.ja va2 s  .  com

    final PiePlot pp = (PiePlot) pc.getPlot();
    if (StringUtils.isEmpty(getTooltipFormula()) == false) {
        pp.setToolTipGenerator(new FormulaPieTooltipGenerator(getRuntime(), getTooltipFormula()));
    }
    if (StringUtils.isEmpty(getUrlFormula()) == false) {
        pp.setURLGenerator(new FormulaPieURLGenerator(getRuntime(), getUrlFormula()));
    }

    if (shadowPaint != null) {
        pp.setShadowPaint(shadowPaint);
    }
    if (shadowXOffset != null) {
        pp.setShadowXOffset(shadowXOffset.doubleValue());
    }
    if (shadowYOffset != null) {
        pp.setShadowYOffset(shadowYOffset.doubleValue());
    }

    final CategoryDataset c = mpp.getDataset();
    if (c != null) {
        final String[] colors = getSeriesColor();
        final int keysSize = c.getColumnKeys().size();
        for (int i = 0; i < colors.length; i++) {
            if (keysSize > i) {
                pp.setSectionPaint(c.getColumnKey(i), parseColorFromString(colors[i]));
            }
        }
    }

    if (StringUtils.isEmpty(getLabelFont()) == false) {
        pp.setLabelFont(Font.decode(getLabelFont()));
    }

    if (Boolean.FALSE.equals(getItemsLabelVisible())) {
        pp.setLabelGenerator(null);
    } else {
        final ExpressionRuntime runtime = getRuntime();
        final Locale locale = runtime.getResourceBundleFactory().getLocale();

        final FastDecimalFormat fastPercent = new FastDecimalFormat(FastDecimalFormat.TYPE_PERCENT, locale);
        final FastDecimalFormat fastInteger = new FastDecimalFormat(FastDecimalFormat.TYPE_INTEGER, locale);

        final DecimalFormat numFormat = new DecimalFormat(fastInteger.getPattern(),
                new DecimalFormatSymbols(locale));
        numFormat.setRoundingMode(RoundingMode.HALF_UP);

        final DecimalFormat percentFormat = new DecimalFormat(fastPercent.getPattern(),
                new DecimalFormatSymbols(locale));
        percentFormat.setRoundingMode(RoundingMode.HALF_UP);

        final StandardPieSectionLabelGenerator labelGen = new StandardPieSectionLabelGenerator(
                multipieLabelFormat, numFormat, percentFormat);
        pp.setLabelGenerator(labelGen);
    }
}

From source file:com.opensourcestrategies.activities.reports.ActivitiesChartsService.java

private String createPieChart(DefaultPieDataset dataset, String title)
        throws InfrastructureException, IOException {
    Debug.logInfo("Charting dashboard [" + title + "]", MODULE);
    // set up the chart
    JFreeChart chart = ChartFactory.createPieChart(title, dataset, true, // include legend
            true, // tooltips
            false // urls
    );/*from  w  w w  . j  a va  2  s . c  o  m*/
    chart.setBackgroundPaint(Color.white);
    chart.setBorderVisible(true);
    chart.setPadding(new RectangleInsets(5.0, 5.0, 5.0, 5.0));

    // get a reference to the plot for further customization...
    final PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setCircular(true);
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}: {1} / {2}",
            NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));
    plot.setNoDataMessage("No data available");

    Color[] colors = {
            Color.decode("#" + infrastructure.getConfigurationValue(
                    OpentapsConfigurationTypeConstants.ACTIVITIES_DASHBOARD_LEADS_NEW_COLOR)),
            Color.decode("#" + infrastructure.getConfigurationValue(
                    OpentapsConfigurationTypeConstants.ACTIVITIES_DASHBOARD_LEADS_OLD_COLOR)),
            Color.decode("#" + infrastructure.getConfigurationValue(
                    OpentapsConfigurationTypeConstants.ACTIVITIES_DASHBOARD_LEADS_NO_ACTIVITY_COLOR)) };
    for (int i = 0; i < dataset.getItemCount(); i++) {
        Comparable<?> key = dataset.getKey(i);
        plot.setSectionPaint(key, colors[i]);
    }

    // save as a png and return the file name
    return ServletUtilities.saveChartAsPNG(chart, chartWidth, chartHeight, null);
}

From source file:org.tiefaces.components.websheet.chart.ChartHelper.java

/**
 * finalize the style for jfreechart. The default setting is different from
 * jfreechart and Excel. We try to minimize the difference.
 * //  w  w w . ja v a  2 s  .  c o m
 * @param chart
 *            jfreechart.
 * @param chartData
 *            contain information gathered from excel chart object.
 */

private void setupPieStyle(final JFreeChart chart, final ChartData chartData) {
    PiePlot plot = (PiePlot) chart.getPlot();
    List<ChartSeries> seriesList = chartData.getSeriesList();
    List<ParsedCell> categoryList = chartData.getCategoryList();
    BasicStroke bLine = new BasicStroke(2.0f);
    for (int i = 0; i < seriesList.size(); i++) {
        ChartSeries chartSeries = seriesList.get(i);
        List<XColor> valueColorList = chartSeries.getValueColorList();
        for (int index = 0; index < categoryList.size(); index++) {
            try {
                String sCategory = getParsedCellValue(categoryList.get(index));
                Color cColor = ColorUtility.xssfClrToClr(valueColorList.get(index).getXssfColor());
                plot.setSectionPaint(sCategory, cColor);
                plot.setSectionOutlineStroke(sCategory, bLine);
            } catch (Exception ex) {
                LOG.log(Level.FINE, "SetupPieStyle error = " + ex.getLocalizedMessage(), ex);
            }
        }

    }
    plot.setBackgroundPaint(ColorUtility.xssfClrToClr(chartData.getBgColor().getXssfColor()));

    // below are modifications for default setting in excel chart
    // to-do: need read setting from xml in future

    plot.setOutlineVisible(false);
    plot.setLegendItemShape(new Rectangle(TieConstants.DEFAULT_LEGENT_ITEM_SHAPE_WIDTH,
            TieConstants.DEFAULT_LEGENT_ITEM_SHAPE_HEIGHT));
    chart.setBackgroundPaint(Color.WHITE);
    LegendTitle legend = chart.getLegend();
    legend.setPosition(RectangleEdge.RIGHT);
    legend.setFrame(BlockBorder.NONE);

}

From source file:de.tor.tribes.ui.panels.MinimapPanel.java

private void renderChartInfo() {
    HashMap<Object, Marker> marks = new HashMap<>();
    DefaultPieDataset dataset = buildDataset(marks);

    JFreeChart chart = ChartFactory.createPieChart(null, // chart title
            dataset, // data
            true, // include legend
            true, false);/*from  ww  w .  j  a  va 2  s. c  o  m*/
    chart.setBackgroundPaint(null);
    //chart.setBorderStroke(null);
    chart.setBorderVisible(false);
    final PiePlot plot = (PiePlot) chart.getPlot();
    // plot.setBackgroundPaint(null);
    //  plot.setShadowPaint(null);

    for (Object o : marks.keySet()) {
        if (iCurrentView == ID_ALLY_CHART) {
            Ally a = (Ally) o;
            plot.setSectionPaint(a.getTag(), marks.get(a).getMarkerColor());
        } else {
            Tribe t = (Tribe) o;
            plot.setSectionPaint(t.getName(), marks.get(t).getMarkerColor());
        }
    }
    //plot.setCircular(true);
    //  plot.setMaximumLabelWidth(30.0);
    /*
        * plot.setLabelGenerator(new StandardPieSectionLabelGenerator( "{0} = {2}", NumberFormat.getNumberInstance(),
        * NumberFormat.getPercentInstance()));
        */
    //   chart.getLegend().setVerticalAlignment(VerticalAlignment.CENTER);
    //  chart.getLegend().setPosition(RectangleEdge.RIGHT);
    // plot.setMaximumLabelWidth(20.0);
    plot.setLabelGenerator(null);
    plot.setBackgroundPaint(Constants.DS_BACK);
    /*
     * plot.setInteriorGap(0.0); plot.setLabelGap(0.0);
     */
    plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator("{0} = {2}",
            NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance()));

    /*
     * plot.getL plot.setLabelFont(g2d.getFont().deriveFont(10.0f));
     */

    //plot.setLabelGenerator(null);

    //plot.setMaximumLabelWidth(30.0);
    //plot.getLabelDistributor().distributeLabels(10.0, 20.0);
    //chart.draw(g2d, new Rectangle2D.Float(20, 20, 100, 100));

    //  g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
    plot.setOutlineVisible(false);
    mChartImage = chart.createBufferedImage(getWidth(), getHeight());
    //chart.draw(g2d, new Rectangle2D.Float(50, 50, 400, 400));
    //g2d.drawImage(bi, 30, 30, null);

    //  g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));

    //bi = chart.createBufferedImage(240, 240);
    // g2d.drawImage(bi, 30, 30, null);
}

From source file:org.jfree.eastwood.ChartEngine.java

private static void applyColorsToPiePlot(PiePlot plot, Color[] colors) {
    if (colors.length == 1) {
        Color c = colors[0];//from   w  w w  .ja v  a2s  .  c om
        colors = new Color[2];
        colors[0] = c;
        colors[1] = new Color(255 - ((255 - c.getRed()) / 5), 255 - ((255 - c.getGreen()) / 5),
                255 - ((255 - c.getBlue()) / 5));
    }
    PieDataset dataset = plot.getDataset();
    int sectionCount = dataset.getItemCount();
    if (colors.length < sectionCount) { // we need to interpolate some
                                        // colors
        for (int i = 0; i < colors.length - 1; i++) {
            Color c1 = colors[i];
            Color c2 = colors[i + 1];
            int s1 = sectionIndexForColor(i, colors.length, sectionCount);
            int s2 = sectionIndexForColor(i + 1, colors.length, sectionCount);
            for (int s = s1; s <= s2; s++) {
                Color c = interpolatedColor(c1, c2, s - s1, s2 - s1);
                plot.setSectionPaint(dataset.getKey(s), c);
            }
        }
    } else {
        for (int i = 0; i < sectionCount; i++) {
            plot.setSectionPaint(dataset.getKey(i), colors[i]);
        }
    }
}

From source file:org.orbeon.oxf.processor.serializer.legacy.JFreeChartSerializer.java

protected JFreeChart drawChart(ChartConfig chartConfig, final Dataset ds) {
    JFreeChart chart = null;/*w  w w . j  ava 2s.com*/
    Axis categoryAxis = null;
    if (ds instanceof XYSeriesCollection) {
        categoryAxis = new RestrictedNumberAxis(chartConfig.getCategoryTitle());
    } else if (ds instanceof TimeSeriesCollection) {
        categoryAxis = new DateAxis(chartConfig.getCategoryTitle());
        ((DateAxis) categoryAxis).setDateFormatOverride(new SimpleDateFormat(chartConfig.getDateFormat()));
        if (chartConfig.getCategoryLabelAngle() == 90) {
            ((DateAxis) categoryAxis).setVerticalTickLabels(true);
        } else {
            if (chartConfig.getCategoryLabelAngle() != 0)
                throw new OXFException(
                        "The only supported values of category-label-angle for time-series charts are 0 or 90");
        }
    } else {
        categoryAxis = new CategoryAxis(chartConfig.getCategoryTitle());
        ((CategoryAxis) categoryAxis).setCategoryLabelPositions(chartConfig.getCategoryLabelPosition());
    }
    NumberAxis valueAxis = new RestrictedNumberAxis(chartConfig.getSerieTitle());
    valueAxis.setAutoRangeIncludesZero(chartConfig.getSerieAutoRangeIncludeZero());
    AbstractRenderer renderer = null;
    Plot plot = null;

    switch (chartConfig.getType()) {
    case ChartConfig.VERTICAL_BAR_TYPE:
    case ChartConfig.HORIZONTAL_BAR_TYPE:
        renderer = (ds instanceof ItemPaintCategoryDataset) ? new BarRenderer() {
            public Paint getItemPaint(int row, int column) {
                Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
                if (p != null)
                    return p;
                else
                    return getSeriesPaint(row);
            }
        } : new BarRenderer();

        plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis) categoryAxis, (ValueAxis) valueAxis,
                (CategoryItemRenderer) renderer);

        if (chartConfig.getType() == ChartConfig.VERTICAL_BAR_TYPE)
            ((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
        else
            ((CategoryPlot) plot).setOrientation(PlotOrientation.HORIZONTAL);

        break;
    case ChartConfig.STACKED_VERTICAL_BAR_TYPE:
    case ChartConfig.STACKED_HORIZONTAL_BAR_TYPE:
        renderer = (ds instanceof ItemPaintCategoryDataset) ? new StackedBarRenderer() {
            public Paint getItemPaint(int row, int column) {
                Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
                if (p != null)
                    return p;
                else
                    return getSeriesPaint(row);
            }
        } : new StackedBarRenderer();
        plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis) categoryAxis, (ValueAxis) valueAxis,
                (CategoryItemRenderer) renderer);

        if (chartConfig.getType() == ChartConfig.STACKED_VERTICAL_BAR_TYPE)
            ((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
        else
            ((CategoryPlot) plot).setOrientation(PlotOrientation.HORIZONTAL);
        break;
    case ChartConfig.LINE_TYPE:
        renderer = (ds instanceof ItemPaintCategoryDataset) ? new LineAndShapeRenderer(true, false) {
            public Paint getItemPaint(int row, int column) {
                Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
                if (p != null)
                    return p;
                else
                    return getSeriesPaint(row);
            }
        } : (new LineAndShapeRenderer(true, false));
        plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis) categoryAxis, (ValueAxis) valueAxis,
                (CategoryItemRenderer) renderer);
        ((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
        break;
    case ChartConfig.AREA_TYPE:
        renderer = (ds instanceof ItemPaintCategoryDataset) ? new AreaRenderer() {
            public Paint getItemPaint(int row, int column) {
                Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
                if (p != null)
                    return p;
                else
                    return getSeriesPaint(row);
            }
        } : new AreaRenderer();
        plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis) categoryAxis, (ValueAxis) valueAxis,
                (CategoryItemRenderer) renderer);
        ((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
        break;
    case ChartConfig.VERTICAL_BAR3D_TYPE:
    case ChartConfig.HORIZONTAL_BAR3D_TYPE:
        categoryAxis = new CategoryAxis3D(chartConfig.getCategoryTitle());
        valueAxis = new NumberAxis3D(chartConfig.getSerieTitle());
        renderer = (ds instanceof ItemPaintCategoryDataset) ? new BarRenderer3D() {
            public Paint getItemPaint(int row, int column) {
                Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
                if (p != null)
                    return p;
                else
                    return getSeriesPaint(row);
            }
        } : new BarRenderer3D();
        plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis) categoryAxis, (ValueAxis) valueAxis,
                (CategoryItemRenderer) renderer);

        if (chartConfig.getType() == ChartConfig.VERTICAL_BAR3D_TYPE)
            ((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
        else
            ((CategoryPlot) plot).setOrientation(PlotOrientation.HORIZONTAL);

        break;
    case ChartConfig.STACKED_VERTICAL_BAR3D_TYPE:
    case ChartConfig.STACKED_HORIZONTAL_BAR3D_TYPE:
        categoryAxis = new CategoryAxis3D(chartConfig.getCategoryTitle());
        valueAxis = new NumberAxis3D(chartConfig.getSerieTitle());
        renderer = (ds instanceof ItemPaintCategoryDataset) ? new StackedBarRenderer3D() {
            public Paint getItemPaint(int row, int column) {
                Paint p = ((ItemPaintCategoryDataset) ds).getItemPaint(row, column);
                if (p != null)
                    return p;
                else
                    return getSeriesPaint(row);
            }
        } : new StackedBarRenderer3D();
        plot = new CategoryPlot((CategoryDataset) ds, (CategoryAxis) categoryAxis, (ValueAxis) valueAxis,
                (CategoryItemRenderer) renderer);

        if (chartConfig.getType() == ChartConfig.STACKED_VERTICAL_BAR3D_TYPE)
            ((CategoryPlot) plot).setOrientation(PlotOrientation.VERTICAL);
        else
            ((CategoryPlot) plot).setOrientation(PlotOrientation.HORIZONTAL);

        break;
    case ChartConfig.PIE_TYPE:
    case ChartConfig.PIE3D_TYPE:
        categoryAxis = null;
        valueAxis = null;
        renderer = null;
        ExtendedPieDataset pds = (ExtendedPieDataset) ds;

        plot = chartConfig.getType() == ChartConfig.PIE_TYPE ? new PiePlot(pds) : new PiePlot3D(pds);

        PiePlot pp = (PiePlot) plot;
        pp.setLabelGenerator(new StandardPieSectionLabelGenerator());

        for (int i = 0; i < pds.getItemCount(); i++) {
            Paint p = pds.getPaint(i);
            if (p != null)
                pp.setSectionPaint(i, p);

            pp.setExplodePercent(i, pds.getExplodePercent(i));

            Paint paint = pds.getPaint(i);
            if (paint != null)
                pp.setSectionPaint(i, paint);
        }
        break;
    case ChartConfig.XY_LINE_TYPE:
        renderer = new XYLineAndShapeRenderer(true, false);
        plot = new XYPlot((XYDataset) ds, (ValueAxis) categoryAxis, (ValueAxis) valueAxis,
                (XYLineAndShapeRenderer) renderer);
        break;
    case ChartConfig.TIME_SERIES_TYPE:
        renderer = new XYLineAndShapeRenderer(true, false);
        plot = new XYPlot((XYDataset) ds, (DateAxis) categoryAxis, (ValueAxis) valueAxis,
                (XYLineAndShapeRenderer) renderer);
        break;
    default:
        throw new OXFException("Chart Type not supported");
    }

    if (categoryAxis != null) {
        categoryAxis.setLabelPaint(chartConfig.getTitleColor());
        categoryAxis.setTickLabelPaint(chartConfig.getTitleColor());
        categoryAxis.setTickMarkPaint(chartConfig.getTitleColor());
        if (categoryAxis instanceof RestrictedNumberAxis) {
            ((RestrictedNumberAxis) categoryAxis).setMaxTicks(chartConfig.getMaxNumOfLabels());
        }
        if (categoryAxis instanceof CategoryAxis && chartConfig.getCategoryMargin() != 0)
            ((CategoryAxis) categoryAxis).setCategoryMargin(chartConfig.getCategoryMargin());
    }

    if (valueAxis != null) {
        valueAxis.setLabelPaint(chartConfig.getTitleColor());
        valueAxis.setTickLabelPaint(chartConfig.getTitleColor());
        valueAxis.setTickMarkPaint(chartConfig.getTitleColor());
        ((RestrictedNumberAxis) valueAxis).setMaxTicks(chartConfig.getMaxNumOfLabels());
    }

    if (renderer != null) {
        if (renderer instanceof XYLineAndShapeRenderer) {
            ((XYLineAndShapeRenderer) renderer).setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
        } else {
            ((CategoryItemRenderer) renderer)
                    .setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        }
        if (renderer instanceof BarRenderer)
            ((BarRenderer) renderer).setItemMargin(chartConfig.getBarMargin());

        int j = 0;
        for (Iterator i = chartConfig.getValueIterator(); i.hasNext();) {
            Value v = (Value) i.next();
            renderer.setSeriesPaint(j, v.getColor());
            j++;
        }
    }

    plot.setOutlinePaint(chartConfig.getTitleColor());
    CustomLegend legend = chartConfig.getLegendConfig();
    chart = new JFreeChart(chartConfig.getTitle(), TextTitle.DEFAULT_FONT, plot, false);
    if (legend.isVisible()) {
        legend.setSources(new LegendItemSource[] { plot });
        chart.addLegend(legend);
    }
    chart.setBackgroundPaint(chartConfig.getBackgroundColor());
    TextTitle textTitle = new TextTitle(chartConfig.getTitle(), TextTitle.DEFAULT_FONT,
            chartConfig.getTitleColor(), TextTitle.DEFAULT_POSITION, TextTitle.DEFAULT_HORIZONTAL_ALIGNMENT,
            TextTitle.DEFAULT_VERTICAL_ALIGNMENT, TextTitle.DEFAULT_PADDING);
    chart.setTitle(textTitle);
    return chart;
}

From source file:probe.com.view.body.quantcompare.PieChart.java

private String initPieChart(int width, int height, String title) {
    DefaultPieDataset dataset = new DefaultPieDataset();
    for (int x = 0; x < labels.length; x++) {
        dataset.setValue(labels[x], values[x]);

    }//from   w  w  w. java2 s .c  om
    PiePlot plot = new PiePlot(dataset);
    plot.setNoDataMessage("No data available");
    plot.setCircular(true);

    plot.setLabelGap(0);

    plot.setLabelFont(new Font("Verdana", Font.BOLD, 10));
    plot.setLabelGenerator(new PieSectionLabelGenerator() {

        @Override
        public String generateSectionLabel(PieDataset pd, Comparable cmprbl) {
            return valuesMap.get(cmprbl.toString());
        }

        @Override
        public AttributedString generateAttributedSectionLabel(PieDataset pd, Comparable cmprbl) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });
    plot.setSimpleLabels(true);

    plot.setLabelBackgroundPaint(null);
    plot.setLabelShadowPaint(null);
    plot.setLabelPaint(Color.WHITE);
    plot.setLabelOutlinePaint(null);
    plot.setBackgroundPaint(Color.WHITE);
    plot.setInteriorGap(0);
    plot.setShadowPaint(Color.WHITE);
    plot.setOutlineVisible(false);
    plot.setBaseSectionOutlinePaint(Color.WHITE);
    plot.setSectionOutlinesVisible(true);
    plot.setBaseSectionOutlineStroke(new BasicStroke(1.2f));
    plot.setInteriorGap(0.05);
    for (String label : labels) {
        plot.setSectionPaint(label, defaultKeyColorMap.get(label));
    }

    JFreeChart chart = new JFreeChart(plot);
    //        chart.setTitle(new TextTitle(title, new Font("Verdana", Font.BOLD, 13)));
    chart.setBorderPaint(null);
    chart.setBackgroundPaint(null);
    chart.getLegend().setFrame(BlockBorder.NONE);
    chart.getLegend().setItemFont(new Font("Verdana", Font.PLAIN, 10));
    String imgUrl = saveToFile(chart, width, height);

    return imgUrl;

}

From source file:beproject.MainGUI.java

void createCountryPieChart() throws SQLException {
    DefaultPieDataset dataset = new DefaultPieDataset();
    String tmp = "select country, count(country) from tweets where moviename='" + movieName
            + "' group by country";
    ResultSet rs = stmt.executeQuery(tmp);
    while (rs.next()) {
        String tmp1 = rs.getString(1);
        if (tmp1.equals(""))
            tmp1 = "Others";
        dataset.setValue(tmp1, rs.getInt(2));
    }/*  w w  w.ja  v  a 2 s .  co  m*/

    PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator("{0}: {1} ({2})",
            new DecimalFormat("0"), new DecimalFormat("0.00%"));

    JFreeChart chart = ChartFactory.createPieChart("Tweets by Country", dataset, true, true, false);
    PiePlot p = (PiePlot) chart.getPlot();
    p.setSectionPaint("Others", Color.gray);
    //p.setSectionPaint(KEY2, Color.red);
    //p.setExplodePercent(KEY1, 0.10);
    p.setSimpleLabels(true);
    p.setLabelGenerator(gen);
    if (countryPieChart == null) {
        countryPieChart = new ChartPanel(chart);
        countryPanel.add(countryPieChart);
    } else {
        countryPanel.remove(countryPieChart);
        countryPieChart = new ChartPanel(chart);
        countryPanel.add(countryPieChart);
    }

    countryPanel.validate();
}

From source file:beproject.MainGUI.java

void createPieChart() throws SQLException {
    DefaultPieDataset dataset = new DefaultPieDataset();
    String tmp = "select polarity, count(polarity) from tweets where moviename='" + movieName
            + "' group by polarity";
    ResultSet rs = stmt.executeQuery(tmp);
    while (rs.next()) {
        int a = rs.getInt(1);
        switch (a) {
        case 4:/*from  ww w  . j ava 2  s .c o  m*/
            dataset.setValue("Very Positive", rs.getInt(2));
            break;
        case 3:
            dataset.setValue("Positive", rs.getInt(2));
            break;
        case 2:
            dataset.setValue("Neutral", rs.getInt(2));
            break;
        case 1:
            dataset.setValue("Negative", rs.getInt(2));
            break;
        case 0:
            dataset.setValue("Very Negative", rs.getInt(2));
            break;
        }
    }

    JFreeChart chart = ChartFactory.createPieChart("Sentiment Analysis", dataset, true, true, false);
    chart.setBackgroundPaint(Color.WHITE);
    chart.setBorderVisible(false);
    PiePlot p = (PiePlot) chart.getPlot();
    //p.setSectionPaint("Very Negative", Color.BLACK);
    p.setSectionPaint("Negative", Color.BLACK);
    //p.setSectionPaint("Neutral", new Color(3, 156, 248));
    //p.setSectionPaint("Positive", new Color(96, 194, 253));
    //p.setSectionPaint("Very Positive", new Color(0xffffff));
    p.setSimpleLabels(true);
    ChartUtilities.applyCurrentTheme(chart);
    if (pieChart == null) {
        pieChart = new ChartPanel(chart);
        sentimentPanel.add(pieChart);
    } else {
        sentimentPanel.remove(pieChart);
        pieChart = new ChartPanel(chart);
        sentimentPanel.add(pieChart);
    }
    pieChart.setBackground(Color.WHITE);
    sentimentPanel.validate();
}

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).    /*from   w w w.  java  2 s.  c  o  m*/
* <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 locale  the locale (<code>null</code> not permitted).    
* @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.    
*     
* @since 1.0.7    
*/
public static JFreeChart createPieChart(String title, PieDataset dataset, PieDataset previousDataset,
        int percentDiffForMaxScale, boolean greenForIncrease, boolean legend, boolean tooltips, Locale locale,
        boolean subTitle, boolean showDifference) {

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

    if (tooltips) {
        plot.setToolTipGenerator(new StandardPieToolTipGenerator(locale));
    }

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