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:pe.egcc.app.demo.Demo02.java

private void btnMostrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnMostrarActionPerformed
    // Definiendo la fuente de datos
    DefaultPieDataset data = new DefaultPieDataset();
    data.setValue("Artculo 1", 40.55);
    data.setValue("Artculo 2", 81.23);
    data.setValue("Artculo 3", 61.54);

    // Creando el grfico
    JFreeChart chart = ChartFactory.createPieChart("Ejemplo de Grfico Tipo Pastel", // Ttulo del grfico
            data, // DataSet
            true, // Leyenda
            true, // ToolTips
            true);/*  w  w  w.  j  a v  a 2  s.  c om*/

    // Dibujando el grfico en un jPanel
    BufferedImage imagen = chart.createBufferedImage(panelGrafico.getWidth() - 2, panelGrafico.getHeight() - 2);
    panelGrafico.getGraphics().drawImage(imagen, 1, 1, null);
}

From source file:graficos.GenerarGraficoPromociones.java

public void crear() throws ParseException {
    DefaultPieDataset pieDataset = new DefaultPieDataset();
    ArrayList<String> reservaciones = new ArrayList();
    try {/*from  w  ww  .j a va 2 s.c o  m*/
        Dba db = new Dba(pathdb);
        db.conectar();
        String sql = "select FechaReservacion from Reservacion join Habitacion on Reservacion.IdHabitacion=Habitacion.IdHabitacion "
                + " where Habitacion.IdCategoria=" + idcategoria;
        db.prepare(sql);
        db.query.execute();
        ResultSet rs = db.query.getResultSet();

        while (rs.next()) {
            reservaciones.add(rs.getString(1));
        }
        db.desconectar();
    } catch (Exception e) {

    }
    ArrayList<String> promociones = new ArrayList();
    try {
        Dba db = new Dba(pathdb);
        db.conectar();
        String sql = "select Tipo, FechaInicio, FechaFin,Porcentaje from CategoriaDescuentoPromocion where IdCategoria="
                + idcategoria;
        db.prepare(sql);
        db.query.execute();
        ResultSet rs = db.query.getResultSet();
        while (rs.next()) {
            promociones.add(
                    rs.getString(1) + "," + rs.getString(2) + "," + rs.getString(3) + "," + rs.getString(4));
        }
        db.desconectar();
    } catch (Exception e) {

    }
    int[] count = new int[promociones.size() + 1];
    for (int i = 0; i < reservaciones.size(); i++) {
        int si = 0;
        for (int j = 0; j < promociones.size(); j++) {
            String[] partes = promociones.get(j).split(",");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date fechain = format.parse(partes[1]);
            Date fechafi = format.parse(partes[2]);
            Date fechare = format.parse(reservaciones.get(i));
            if (fechare.compareTo(fechain) >= 0 && fechare.compareTo(fechafi) <= 0) {
                si++;
                count[j]++;
            }
        }
        if (si == 0) {
            count[promociones.size()]++;
        }
    }
    for (int j = 0; j < count.length; j++) {
        if (j == promociones.size()) {
            pieDataset.setValue("Precio Normal", new Integer(count[j]));
        } else {
            String[] partes = promociones.get(j).split(",");
            pieDataset.setValue("desc: " + partes[3] + "%", new Integer(count[j]));
        }

    }
    JFreeChart chart = ChartFactory.createPieChart(
            "Porcentaje de Reservaciones Precio Normal vs Promociones y Descuentos", pieDataset, true, true,
            false);
    PiePlot plot = (PiePlot) chart.getPlot();
    PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator("{0}: {1} ({2})",
            new DecimalFormat("0"), new DecimalFormat("0%"));
    plot.setLabelGenerator(gen);
    try {
        ChartUtilities.saveChartAsJPEG(new File(path), chart, 500, 300);
    } catch (Exception ee) {
        System.err.println(ee.toString());
        System.err.println("Problem occurred creating chart.");
    }
}

From source file:org.getobjects.samples.HelloChart.Main.java

/**
 * This defines the direct action which can be invoked using:<pre>
 *   /HelloThumbnail/wa/Main/chart?chs=128x128&chartType=p3</pre>
 * /*from  www  .  ja  va  2 s  .co  m*/
 * <p>
 * Note that the method returns a java.awt.BufferedImage. This will get
 * rendered to a GIF image by the GoDefaultRenderer.
 * (this method does not return a WOResponse, but it lets the Go machinery
 * deal with the image result object). 
 * 
 * @return a BufferedImage containing the scaled image
 */
public Object chartAction() {
    Dimension size = UGoogleChart.getDimensions(F("chs", "128x128"), null);
    String chartType = (String) F("cht", "p");

    JFreeChart chart = null;
    if (chartType.equals("p")) {
        chart = ChartFactory.createPieChart((String) F("title", "Revenue Chart" /* default title */),
                this.getPieDataset(), UObject.boolValue(F("legend", true)) /* show legend */,
                UObject.boolValue(F("tooltips", true)) /* show tooltips */, false /* no URLs */);
    } else if (chartType.equals("p3")) {
        chart = ChartFactory.createPieChart3D((String) F("title", "Revenue Chart" /* default title */),
                this.getPieDataset(), UObject.boolValue(F("legend", true)) /* show legend */,
                UObject.boolValue(F("tooltips", true)) /* show tooltips */, false /* no URLs */);
    } else if (chartType.startsWith("b")) {
        // bhs, bvs (one bar with multiple values)
        // bhg, bvg (one bar for each row)

        PlotOrientation orientation = PlotOrientation.VERTICAL;
        if (chartType.startsWith("bh"))
            orientation = PlotOrientation.HORIZONTAL;

        if (chartType.endsWith("3")) {
            chart = ChartFactory.createBarChart3D((String) F("title", "Revenue Chart" /* default title */),
                    (String) F("xlabel", "X-Axis"), (String) F("ylabel", "Y-Axis"), getCatDataSet(),
                    orientation, UObject.boolValue(F("legend", true)) /* show legend */,
                    UObject.boolValue(F("tooltips", true)) /* show tooltips */, false /* no URLs */);
        } else {
            chart = ChartFactory.createBarChart((String) F("title", "Revenue Chart" /* default title */),
                    (String) F("xlabel", "X-Axis"), (String) F("ylabel", "Y-Axis"), getRevCatDataSet(),
                    orientation, UObject.boolValue(F("legend", true)) /* show legend */,
                    UObject.boolValue(F("tooltips", true)) /* show tooltips */, false /* no URLs */);
        }
    }

    /* style the chart */

    chart.setBorderVisible(true);
    //chart.setBorderPaint(new Paint(Color.blue));

    Paint p = new GradientPaint(0, 0, Color.white, 1000, 0, Color.blue);
    chart.setBackgroundPaint(p);

    /* style the plot */

    Plot plot = chart.getPlot();
    plot.setBackgroundPaint(new Color(240, 240, 250));

    /* add explosion for Pies */

    if (plot instanceof PiePlot) {
        PiePlot pplot = (PiePlot) chart.getPlot();
        pplot.setExplodePercent("Products", 0.30); // can be multiple explodes
    }

    /* create the image for HTTP delivery */

    return chart.createBufferedImage(size.width, size.height);
}

From source file:sentimentanalyzer.ChartController.java

public void createAndPopulatePieChart__TESTER(JPanel pnlPieChart) {

    DefaultPieDataset data = new DefaultPieDataset();

    data.setValue(Pos, 0 /*count for 1 */);
    data.setValue(Neu, 0 /*count for 0 */);
    data.setValue(Neg, 0 /*count for -1 */);

    JFreeChart chart = ChartFactory.createPieChart("Sent. Distr. for Testing", data, false, // legend?
            false, // tooltips?
            false // URLs?
    );//  w  w w . jav a  2s  . c om
    ChartPanel CP = new ChartPanel(chart);

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

    plot.setSectionPaint("Pie chart is not available", Color.LIGHT_GRAY);
    plot.setExplodePercent(Pos, 0.025);
    plot.setExplodePercent(Neg, 0.025);
    plot.setExplodePercent(Neu, 0.025);

    //Customize PieChart to show absolute values and percentages;

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

    TextTitle legendText = new TextTitle("The total number of tweets: ");
    legendText.setPosition(RectangleEdge.BOTTOM);
    chart.addSubtitle(legendText);

    pnlPieChart.setLayout(new java.awt.BorderLayout());
    pnlPieChart.add(CP, BorderLayout.CENTER);
}

From source file:com.liferay.polls.web.internal.portlet.action.ViewChartMVCResourceCommand.java

@Override
protected void doServeResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
        throws Exception {

    try {//from www. java 2 s .  c  o  m
        ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);

        long questionId = ParamUtil.getLong(resourceRequest, "questionId");

        String chartType = ParamUtil.getString(resourceRequest, "chartType", "pie");
        String chartName = themeDisplay.translate("vote-results");
        String xName = themeDisplay.translate("choice");
        String yName = themeDisplay.translate("votes");

        CategoryDataset categoryDataset = PollsUtil.getVotesDataset(questionId);

        JFreeChart jFreeChat = null;

        if (chartType.equals("area")) {
            jFreeChat = ChartFactory.createAreaChart(chartName, xName, yName, categoryDataset,
                    PlotOrientation.VERTICAL, true, false, false);
        } else if (chartType.equals("horizontal_bar")) {
            jFreeChat = ChartFactory.createBarChart(chartName, xName, yName, categoryDataset,
                    PlotOrientation.HORIZONTAL, true, false, false);
        } else if (chartType.equals("line")) {
            jFreeChat = ChartFactory.createLineChart(chartName, xName, yName, categoryDataset,
                    PlotOrientation.VERTICAL, true, false, false);
        } else if (chartType.equals("vertical_bar")) {
            jFreeChat = ChartFactory.createBarChart(chartName, xName, yName, categoryDataset,
                    PlotOrientation.VERTICAL, true, false, false);
        } else {
            PieDataset pieDataset = DatasetUtilities.createPieDatasetForRow(categoryDataset, 0);

            jFreeChat = ChartFactory.createPieChart(chartName, pieDataset, true, false, false);
        }

        resourceResponse.setContentType(ContentTypes.IMAGE_JPEG);

        OutputStream outputStream = resourceResponse.getPortletOutputStream();

        ChartUtilities.writeChartAsJPEG(outputStream, jFreeChat, 400, 400);
    } catch (Exception e) {
        PortletSession portletSession = resourceRequest.getPortletSession();

        PortletContext portletContext = portletSession.getPortletContext();

        PortletRequestDispatcher requestDispatcher = portletContext.getRequestDispatcher("/polls/error.jsp");

        requestDispatcher.forward(resourceRequest, resourceResponse);
    }
}

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

@SuppressWarnings("static-access")
@Override/*from   w ww.java 2  s  .c  o m*/
protected JFreeChart createChart(Map<String, Object> model, HttpServletRequest request) {

    UserContext userContext = Context.getUserContext();
    ApplicationContext appContext = ContextProvider.getApplicationContext();
    PmtctService pmtct = Context.getService(PmtctService.class);
    DefaultPieDataset pieDataset = new DefaultPieDataset();

    List<Object> objects = null;
    PMTCTModuleTag tag = new PMTCTModuleTag();

    List<String> hivOptions = new ArrayList<String>();
    List<Integer> hivOptionValues = new ArrayList<Integer>();
    Collection<ConceptAnswer> answers = Context.getConceptService()
            .getConcept(PMTCTConstants.RESULT_OF_HIV_TEST).getAnswers();
    try {
        objects = pmtct.getCurrentPatientsInPmtct();
        for (ConceptAnswer str : answers) {
            hivOptions.add(str.getAnswerConcept().getName().getName());
            hivOptionValues.add(0);
        }
        hivOptions.add("Others");
        hivOptionValues.add(0);

        for (Object ob : objects) {
            int patientId = (Integer) ((Object[]) ob)[0];
            String patientHivStatus = tag.lastObsValueByConceptId(patientId, PMTCTConstants.RESULT_OF_HIV_TEST);

            int i = 0;
            boolean found = false;
            for (String s : hivOptions) {
                if ((s.compareToIgnoreCase(patientHivStatus)) == 0) {
                    hivOptionValues.set(i, hivOptionValues.get(i) + 1);
                    found = true;
                }
                i++;
            }

            if (!found) {
                hivOptionValues.set(hivOptionValues.size() - 1,
                        hivOptionValues.get(hivOptionValues.size() - 1) + 1);
            }

        }

        int i = 0;
        for (String s : hivOptions) {
            if (hivOptionValues.get(i) > 0) {
                Float percentage = new Float(100 * hivOptionValues.get(i) / objects.size());
                pieDataset.setValue(s + " (" + hivOptionValues.get(i) + " , " + percentage + "%)", percentage);
            }
            i++;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    String title = appContext.getMessage("pmtct.menu.patientInPmtct", null, userContext.getLocale());

    JFreeChart chart = ChartFactory.createPieChart(title + " : " + Context.getConceptService()
            .getConcept(PMTCTConstants.HIV_STATUS).getPreferredName(userContext.getLocale()), pieDataset, true,
            true, false);

    return chart;
}

From source file:by.bsu.zmiecer.PieChartDemo1.java

/**
 * Creates a chart./*www  . jav  a 2 s  .  c  o m*/
 *
 * @param dataset  the dataset.
 *
 * @return A chart.
 */
private static JFreeChart createChart(PieDataset dataset) {

    JFreeChart chart = ChartFactory.createPieChart("   ", // chart title
            dataset, // data
            false, // no legend
            true, // tooltips
            false // no URL generation
    );

    // set a custom background for the chart
    chart.setBackgroundPaint(
            new GradientPaint(new Point(0, 0), new Color(0, 255, 11), new Point(400, 200), Color.BLUE));

    // customise the title position and font
    TextTitle t = chart.getTitle();
    t.setHorizontalAlignment(HorizontalAlignment.LEFT);
    t.setPaint(new Color(240, 240, 240));
    t.setFont(new Font("Arial", Font.BOLD, 26));

    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(null);
    plot.setInteriorGap(0.04);
    plot.setOutlineVisible(false);

    // use gradients and white borders for the section colours
    //plot.setSectionPaint("Others", createGradientPaint(new Color(200, 200, 255), Color.BLUE));
    //plot.setSectionPaint("Samsung", createGradientPaint(new Color(255, 200, 200), Color.RED));
    //plot.setSectionPaint("Apple", createGradientPaint(new Color(200, 255, 200), Color.GREEN));
    //plot.setSectionPaint("Nokia", createGradientPaint(new Color(200, 255, 200), Color.YELLOW));
    plot.setBaseSectionOutlinePaint(Color.WHITE);
    plot.setSectionOutlinesVisible(true);
    plot.setBaseSectionOutlineStroke(new BasicStroke(2.0f));

    // customise the section label appearance
    plot.setLabelFont(new Font("Courier New", Font.BOLD, 20));
    plot.setLabelLinkPaint(Color.WHITE);
    plot.setLabelLinkStroke(new BasicStroke(2.0f));
    plot.setLabelOutlineStroke(null);
    plot.setLabelPaint(Color.WHITE);
    plot.setLabelBackgroundPaint(null);

    /*
    // add a subtitle giving the data source
    TextTitle source = new TextTitle("Source: http://www.bbc.co.uk/news/business-15489523",
        new Font("Courier New", Font.PLAIN, 12));
    source.setPaint(Color.WHITE);
    source.setPosition(RectangleEdge.BOTTOM);
    source.setHorizontalAlignment(HorizontalAlignment.RIGHT);
    chart.addSubtitle(source);
    */
    return chart;

}

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

/**
 * Creates a chart./*from ww w. ja v  a 2  s. com*/
 * 
 * @param dataset  the dataset.
 * 
 * @return a chart.
 */
private JFreeChart createChart(final PieDataset dataset) {

    final JFreeChart chart = ChartFactory.createPieChart("Pie Chart Demo 5", // chart title
            dataset, // data
            false, // include legend
            true, false);

    final PiePlot plot = (PiePlot) chart.getPlot();
    plot.setInteriorGap(0.0);
    plot.setLabelGenerator(null);
    return chart;

}

From source file:org.gaixie.micrite.car.action.CarfileChartAction.java

/**
 * 2D/*from w  w  w. j  av a  2  s  .c  om*/
 * @return "success"
 */
public String getPieChart() {
    PieDataset pd = CarfileService.getCarDictionaryPieDataset(this.getQueryBean());
    chart = ChartFactory.createPieChart(getText("?"), pd, true, true, false);
    PieStyle.styleOne(chart);
    this.putChartResultList(chart);
    return SUCCESS;
}

From source file:org.gaixie.micrite.enterprise.action.EnterpriseChartAction.java

/**
 * 2D//from   ww  w. j a va  2s .  c  om
 * @return "success"
 */
public String getPieChart() {
    PieDataset pd = enterpriseService.getEnterpriseSourcePieDataset(this.getQueryBean());
    chart = ChartFactory.createPieChart(getText("?"), pd, true, true, false);
    PieStyle.styleOne(chart);
    this.putChartResultList(chart);
    return SUCCESS;
}