Example usage for org.jfree.chart ChartFactory createPieChart

List of usage examples for org.jfree.chart ChartFactory createPieChart

Introduction

In this page you can find the example usage for org.jfree.chart ChartFactory createPieChart.

Prototype

public static JFreeChart createPieChart(String title, PieDataset dataset, boolean legend, boolean tooltips,
        boolean urls) 

Source Link

Document

Creates a pie chart with default settings.

Usage

From source file:org.openmrs.module.pmtct.web.view.chart.InfantPCRPieChartView.java

/**
 * @see org.openmrs.module.pmtct.web.view.chart.AbstractChartView#createChart(java.util.Map,
 *      javax.servlet.http.HttpServletRequest)
 *///from   ww  w .j  a va 2s  .  co  m
@Override
protected JFreeChart createChart(Map<String, Object> model, HttpServletRequest request) {
    UserContext userContext = Context.getUserContext();
    ApplicationContext appContext = ContextProvider.getApplicationContext();
    PMTCTModuleTag tag = new PMTCTModuleTag();

    List<Object> res = new ArrayList<Object>();

    DefaultPieDataset pieDataset = new DefaultPieDataset();
    String title = "", descriptionTitle = "", dateInterval = "";
    Concept concept = null;
    SimpleDateFormat df = Context.getDateFormat();

    //            Date myDate1 = new Date("1/1/" + ((new Date()).getYear() + 1900));
    //            String startDate1 = df.format(myDate1);

    Date today = new Date();
    Date oneYearFromNow = new Date(new Date().getTime() - PMTCTConstants.YEAR_IN_MILLISECONDS);

    String endDate1 = df.format(today);
    String startDate1 = df.format(oneYearFromNow);

    dateInterval = "(" + new SimpleDateFormat("dd-MMM-yyyy").format(oneYearFromNow) + " - "
            + new SimpleDateFormat("dd-MMM-yyyy").format(today) + ")";

    try {

        PmtctService pmtct;
        pmtct = Context.getService(PmtctService.class);
        try {
            res = pmtct.getGeneralStatForInfantTests_Charting_PCR(startDate1, endDate1);
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        List<String> hivTestResultOptions = new ArrayList<String>();

        List<Integer> pcr_hivTestResultValues = new ArrayList<Integer>();

        Collection<ConceptAnswer> answers = Context.getConceptService()
                .getConcept(PMTCTConstants.RESULT_OF_HIV_TEST).getAnswers();
        for (ConceptAnswer str : answers) {
            hivTestResultOptions.add(str.getAnswerConcept().getName().getName());

            pcr_hivTestResultValues.add(0);
        }
        hivTestResultOptions.add("Others");
        pcr_hivTestResultValues.add(0);

        for (Object ob : res) {
            int val = 0;
            String temp = "", pcr_hivTestResult = "";

            temp = "" + ((Object[]) ob)[2];
            val = (temp.compareTo("") == 0) ? 0 : Integer.parseInt(temp);
            if (val > 0)
                pcr_hivTestResult = tag.getConceptNameById(temp);

            int i = 0;
            boolean pcr_found = false;
            for (String s : hivTestResultOptions) {
                if ((s.compareToIgnoreCase(pcr_hivTestResult)) == 0) {
                    pcr_hivTestResultValues.set(i, pcr_hivTestResultValues.get(i) + 1);
                    pcr_found = true;
                }
                i++;
            }

            if (!pcr_found) {
                pcr_hivTestResultValues.set(pcr_hivTestResultValues.size() - 1,
                        pcr_hivTestResultValues.get(pcr_hivTestResultValues.size() - 1) + 1);
            }
        }

        int i = 0;
        for (String s : hivTestResultOptions) {
            if (pcr_hivTestResultValues.get(i) > 0) {
                Float percentage = new Float(100 * pcr_hivTestResultValues.get(i) / res.size());
                pieDataset.setValue(s + " (" + pcr_hivTestResultValues.get(i) + " , " + percentage + "%)",
                        percentage);
            }
            i++;
        }

        title = appContext.getMessage("pmtct.menu.infantTest", null, userContext.getLocale());
        concept = null;
        descriptionTitle = Context.getEncounterService()
                .getEncounterType(PMTCTConfigurationUtils.getPCRTestEncounterTypeId()).getName();
        descriptionTitle += dateInterval;
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    JFreeChart chart = ChartFactory.createPieChart(title + " : "
            + ((null != concept) ? concept.getPreferredName(userContext.getLocale()) : descriptionTitle),
            pieDataset, true, true, false);

    return chart;
}

From source file:flight_ranker.my_Jframe.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    DefaultPieDataset piedataset = new DefaultPieDataset();
    piedataset.setValue("One", new Integer(10));
    piedataset.setValue("Two", new Integer(20));
    piedataset.setValue("Three", new Integer(30));
    piedataset.setValue("Four", new Integer(40));

    JFreeChart chart = ChartFactory.createPieChart("Pie chart", piedataset, true, true, true);
    PiePlot P = (PiePlot) chart.getPlot();
    //P.setForegroundAlpha(TOP_ALIGNMENT);
    ChartFrame frame = new ChartFrame("Pie chart", chart);
    frame.setVisible(true);/* w w w.j  a  va  2 s .  c o m*/
    frame.setSize(450, 500);
}

From source file:org.deegree.graphics.charts.ChartsBuilder.java

/**
 * Create a pie 2D/3D Pie Chart//www  .ja  v a  2  s . c o m
 *
 * @param title
 *
 * @param keyedValues
 *            The key/value pairs used for the pie chart
 * @param width
 *            of the output image
 * @param height
 *            height of the output image
 * @param is3D
 *            is a 3D Chart
 * @param legend
 *            for the output chart
 * @param tooltips
 *            for the output chart
 * @param lblType
 *            Possible types are <i>Key</i>, <i>Value</i>, <i>KeyValue</i>
 * @param imageType
 *            of the output image
 * @param chartConfigs
 *            to configure the output chart, or null to use the default ChartConfig
 * @return BufferedImage representing the generated chart
 */
public BufferedImage createPieChart(String title, QueuedMap<String, Double> keyedValues, int width, int height,
        boolean is3D, boolean legend, boolean tooltips, String lblType, String imageType,
        ChartConfig chartConfigs) {

    DefaultPieDataset dataset = new DefaultPieDataset();
    Iterator<String> it = keyedValues.keySet().iterator();
    while (it.hasNext()) {
        String key = it.next();
        if ("KeyValue".equals(lblType)) {
            dataset.setValue(StringTools.concat(20, key, " ", keyedValues.get(key)), keyedValues.get(key));
        } else if ("Value".equals(lblType)) {
            dataset.setValue(keyedValues.get(key), keyedValues.get(key));
        } else {
            dataset.setValue(key, keyedValues.get(key));
        }
    }
    JFreeChart chart = null;
    if (is3D) {
        chart = ChartFactory.createPieChart3D(title, dataset, legend, tooltips, false);
    } else {
        chart = ChartFactory.createPieChart(title, dataset, legend, tooltips, true);
    }
    if (chartConfigs == null) {
        chartConfigs = this.chartConfigs;
    }
    return createBufferedImage(configPieChart(chart, chartConfigs), width, height, imageType);
}

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

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

    logger.debug("Generating " + chartType);

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

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

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

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

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

    // Return chart
    JFreeChart chart = null;

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

        setCategoryChartParameters(chart, conf);

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

        setCategoryChartParameters(chart, conf);

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

        setCategoryChartParameters(chart, conf);

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

        setCategoryChartParameters(chart, conf);

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

        setCategoryChartParameters(chart, conf);

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

        setPieChartParameters(chart, conf);

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

        setPieChartParameters(chart, conf);

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

        setPieChartParameters(chart, conf);

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

        setPieChartParameters(chart, conf);

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

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

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

        setCategoryChartParameters(chart, conf);

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

        setCategoryChartParameters(chart, conf);

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

        setCategoryChartParameters(chart, conf);

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

        setCategoryChartParameters(chart, conf);

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

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

    setCommonParameters(chart, conf);

    return chart;
}

From source file:com.ohalo.cn.awt.JFreeChartTest.java

public List<JFreeChart> printHardDiskCharts() throws SigarException {
    Sigar sigar = new Sigar();
    FileSystem fslist[] = sigar.getFileSystemList();
    ArrayList<JFreeChart> charts = new ArrayList<JFreeChart>();

    for (int i = 0; i < fslist.length; i++) {
        FileSystem fs = fslist[i];

        String diskName = fs.getDevName();

        FileSystemUsage usage = null;/*ww  w  .  j  a va  2 s. c  om*/
        try {
            usage = sigar.getFileSystemUsage(fs.getDirName());
        } catch (SigarException e) {
            if (fs.getType() == 2)
                throw e;
            continue;
        }

        DefaultPieDataset dpd = new DefaultPieDataset(); // 

        if (fs.getType() == 2) {
            dpd.setValue("??(" + usage.getAvail() / 1024 / 1024 + "GB)",
                    usage.getAvail());
            dpd.setValue("?(" + usage.getUsed() / 1024 / 1024 + "GB)", usage.getUsed());
        }
        JFreeChart chart = ChartFactory.createPieChart("???", dpd, true, true,
                false);

        chart.setTitle(":" + diskName);
        Font font2 = new Font("", Font.BOLD, 12);
        chart.getTitle().setFont(font2);
        PiePlot pieplot = (PiePlot) chart.getPlot();
        pieplot.setLabelFont(font2);
        chart.getLegend().setItemFont(font2);
        charts.add(chart);
    }

    return charts;
}

From source file:de.dekarlab.moneybuilder.view.AnalyticsView.java

/**
 * Create pie chart./* w ww .j  av  a 2 s  .c o  m*/
 * 
 * @param dataset
 * @param title
 * @return
 */
protected JFreeChart createPieChart(final PieDataset dataset, final String title) {
    final JFreeChart chart = ChartFactory.createPieChart(title, dataset, true, true, false);
    final PiePlot plot = (PiePlot) chart.getPlot();
    plot.setNoDataMessage(App.getGuiProp("report.nodata.msg"));
    plot.setCircular(true);
    // plot.set
    plot.setLabelGap(0.02);
    plot.setBackgroundPaint(Color.white);
    chart.removeLegend();
    plot.setBackgroundPaint(Color.white);
    Iterator<?> it = dataset.getKeys().iterator();
    int color = 0;
    while (it.hasNext()) {
        plot.setSectionPaint((String) it.next(), COLORS[color]);
        color++;
        if (COLORS.length == color) {
            color = 0;
        }
    }
    plot.setLabelBackgroundPaint(Color.white);
    StandardPieSectionLabelGenerator slbl = new StandardPieSectionLabelGenerator("{0} {2} ({1})",
            new DecimalFormat("#,##0"), new DecimalFormat("0%"));
    plot.setLabelGenerator(slbl);
    plot.setLabelFont(new Font("Helvetica", Font.PLAIN, 14));
    plot.setLabelOutlinePaint(Color.white);
    plot.setLabelShadowPaint(Color.white);
    plot.setShadowPaint(Color.white);
    plot.setIgnoreZeroValues(true);
    return chart;
}

From source file:com.itemanalysis.jmetrik.graph.piechart.PieChartPanel.java

public void setGraph() {
    if (hasGroupVariable) {
        DefaultCategoryDataset piedat = new DefaultCategoryDataset();
        chart = ChartFactory.createMultiplePieChart(chartTitle, piedat, TableOrder.BY_ROW, showLegend, true,
                false);//from w  w w .  ja  v  a 2s.co  m

        if (chartSubtitle != null && !"".equals(chartSubtitle)) {
            TextTitle subtitle1 = new TextTitle(chartSubtitle);
            chart.addSubtitle(subtitle1);
        }

        MultiplePiePlot plot = (MultiplePiePlot) chart.getPlot();
        JFreeChart subchart = plot.getPieChart();
        PiePlot p = (PiePlot) subchart.getPlot();
        p.setBackgroundPaint(Color.WHITE);
        p.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({2})"));
        if (explode)
            p.setExplodePercent(explodeValue, explodePercent);

        ChartPanel panel = new ChartPanel(chart);
        panel.setPreferredSize(new Dimension(width, height));

        chart.setPadding(new RectangleInsets(20.0, 5.0, 20.0, 5.0));
        this.add(panel);
    } else {
        DefaultPieDataset piedat = new DefaultPieDataset();
        if (command.getSelectOneOption("view").isValueSelected("3D")) {
            chart = ChartFactory.createPieChart3D(chartTitle, piedat, showLegend, true, false);

            PiePlot3D plot = (PiePlot3D) chart.getPlot();
            plot.setStartAngle(290);
            plot.setDirection(Rotation.CLOCKWISE);
            plot.setForegroundAlpha(0.5f);
            plot.setNoDataMessage("No data to display");
            if (explode)
                plot.setExplodePercent(explodeValue, explodePercent);

        } else {
            chart = ChartFactory.createPieChart(command.getFreeOption("title").getString(), piedat, showLegend,
                    true, false);
        }

        if (chartSubtitle != null && !"".equals(chartSubtitle)) {
            TextTitle subtitle = new TextTitle(chartSubtitle);
            chart.addSubtitle(subtitle);
        }

        PiePlot plot = (PiePlot) chart.getPlot();
        plot.setLabelGap(0.02);
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} ({2})"));
        plot.setBackgroundPaint(Color.WHITE);
        if (explode)
            plot.setExplodePercent(explodeValue, explodePercent);

        ChartPanel panel = new ChartPanel(chart);
        panel.getPopupMenu().addSeparator();
        this.addJpgMenuItem(this, panel.getPopupMenu());
        panel.setPreferredSize(new Dimension(width, height));

        chart.setPadding(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
        this.setBackground(Color.WHITE);
        this.add(panel);
    }

}

From source file:edu.isistan.carcha.plugin.editors.DXMIEditor.java

/**
 * Creates the PieChart page./*from   w  ww . ja v a 2  s  . co m*/
 */
void createPieChartPage() {
    result = new DefaultPieDataset();

    JFreeChart chart = ChartFactory.createPieChart("Design Decisions", result, true, true, false);
    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setStartAngle(290);
    plot.setDirection(Rotation.CLOCKWISE);
    plot.setForegroundAlpha(0.5f);

    Composite composite = new Composite(getContainer(), SWT.NONE);
    FillLayout layout = new FillLayout();
    composite.setLayout(layout);
    new ChartComposite(composite, SWT.NONE, chart, true);
    int index = addPage(composite);
    setPageText(index, "Graph");

}

From source file:Visao.Relatorio.Relatorio_QuantidadeReclamacoesSexo.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    datasetDB = controleRelatorio.numeroReclamacoesSexoGrafico();
    chart = ChartFactory.createPieChart("Quantidade de Reclamaes por Sexo", // chart title
            datasetDB, // data
            true, // include legend
            true, true);/*from www . j  a  v a 2 s. c  o m*/

    Grafico_QuantidadeReclamacoesSexo dialog = null;
    dialog = new Grafico_QuantidadeReclamacoesSexo(parent, true, dao, chart);
    dialog.setLocationRelativeTo(null);
    dialog.setVisible(true);
    jButton2.setEnabled(true);
}

From source file:com.ikon.servlet.admin.StatsGraphServlet.java

/**
 * Generate disk statistics// w w w  . ja  v a 2  s  .c o m
 */
public JFreeChart diskStats() throws IOException, ServletException {
    String repHome = null;

    // Allow absolute repository path
    if ((new File(Config.REPOSITORY_HOME)).isAbsolute()) {
        repHome = Config.REPOSITORY_HOME;
    } else {
        repHome = Config.HOME_DIR + File.separator + Config.REPOSITORY_HOME;
    }

    File df = new File(repHome);
    long total = df.getTotalSpace();
    long usable = df.getUsableSpace();
    long used = total - usable;
    String title = "Disk: " + FormatUtil.formatSize(total);

    log.debug("Total space: {}", FormatUtil.formatSize(total));
    log.debug("Usable space: {}", FormatUtil.formatSize(usable));
    log.debug("Used space: {}", FormatUtil.formatSize(used));

    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("Available (" + FormatUtil.formatSize(usable) + ")", usable * 100 / total);
    dataset.setValue("Used (" + FormatUtil.formatSize(used) + ")", used * 100 / total);

    return ChartFactory.createPieChart(title, dataset, true, false, false);
}