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:weka.core.ChartUtils.java

/**
 * Create a pie chart from summary data (i.e. a list of values and their
 * corresponding frequencies)./*w ww .  j a v a  2s  . c o m*/
 * 
 * @param values a list of values for the chart
 * @param freqs a list of corresponding frequencies
 * @param showLabels true if the chart will show labels
 * @param showLegend true if the chart will show a legend
 * @param additionalArgs optional arguments to the renderer (may be null)
 * @return a pie chart
 * @throws Exception if a problem occurs
 */
protected static JFreeChart getPieChartFromSummaryData(List<String> values, List<Double> freqs,
        boolean showLabels, boolean showLegend, List<String> additionalArgs) throws Exception {

    if (values.size() != freqs.size()) {
        throw new Exception("Number of bins should be equal to number of frequencies!");
    }

    String plotTitle = "Pie Chart";
    String userTitle = getOption(additionalArgs, "-title");
    plotTitle = (userTitle != null) ? userTitle : plotTitle;
    String xLabel = getOption(additionalArgs, "-x-label");
    xLabel = xLabel == null ? "" : xLabel;
    String yLabel = getOption(additionalArgs, "-y-label");
    yLabel = yLabel == null ? "" : yLabel;

    DefaultPieDataset dataset = new DefaultPieDataset();

    for (int i = 0; i < values.size(); i++) {
        String binLabel = values.get(i);
        Number freq = freqs.get(i);

        dataset.setValue(binLabel, freq);
    }

    JFreeChart chart = ChartFactory.createPieChart(plotTitle, // chart title
            dataset, // data
            showLegend, // include legend
            false, false);

    PiePlot plot = (PiePlot) chart.getPlot();
    if (!showLabels) {
        plot.setLabelGenerator(null);
    } else {
        plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
        plot.setNoDataMessage("No data available");
        // plot.setCircular(false);
        plot.setLabelGap(0.02);
    }

    chart.setBackgroundPaint(java.awt.Color.white);
    chart.setTitle(new TextTitle(plotTitle, new Font("SansSerif", Font.BOLD, 12)));

    return chart;
}

From source file:clienteescritorio.MainFrame.java

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
    DefaultPieDataset data = this.getDataForChart();
    /*data.setValue("Category 1", 43.2);
    data.setValue("Category 2", 27.9);//ww w . j  av  a 2 s .  co  m
    data.setValue("Category 3", 79.5);*/
    // create a chart...
    JFreeChart chart = ChartFactory.createPieChart("Grfica de movimientos", data, true, true, true);
    /*
    SELECT a.descripcion,count(ma.idArticulo)
    FROM movArticulo ma, articulo a 
    where a.idArticulo = ma.idArticulo group by a.descripcion; 
    */
    graficaWindow = new Grafica("Grfica", chart);
    graficaWindow.setVisible(true);
    graficaWindow.pack();
    graficaWindow.setMetodosRemotos(metodosRemotos);
}

From source file:UserInterface.DoctorRole.ViewPatientReport.java

private void PiechartBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PiechartBtnActionPerformed
    // TODO add your handling code here:
    DefaultPieDataset dataset = new DefaultPieDataset();
    if (!(patient.getTestDir().getTestdir().isEmpty())) {
        for (Test vs : patient.getTestDir().getTestdir()) {

            dataset.setValue("Blood Pressure", Float.parseFloat(vs.getBloodPressure()));
            dataset.setValue("Blood Platelets", Float.parseFloat(vs.getBloodPlatlets()));
            dataset.setValue("Hemoglobin Level", Float.parseFloat(vs.getHemoglobinLevel()));
            //dataset.addValue(vs.getWeight(), "Weight", vs.getTimestamp());

        }//from   w ww.  j  av  a 2 s.  c  o m
        JFreeChart chartFactory = ChartFactory.createPieChart("Pie Chart", dataset, true, true, true);
        PiePlot p = (PiePlot) chartFactory.getPlot();
        // p.setForegroundAlpha(TOP_ALIGNMENT);
        ChartFrame frame = new ChartFrame("Pie Chart for VitalSign", chartFactory);
        frame.setVisible(true);
        frame.setSize(700, 320);
    } else {
        JOptionPane.showMessageDialog(this, "No Vital Signs To Display On Graph!!!");
    }
}

From source file:UserInterface.CDC.VaccineCityDistributionJPanel.java

private void viewChartjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewChartjButtonActionPerformed
    // TODO add your handling code here:

    DefaultPieDataset pieDataset = new DefaultPieDataset();
    for (CityNetwork city : state.getCityList()) {
        pieDataset.setValue(city.getName(), city.getTotalVaccinesDistributedInCity());

    }// w w  w. j ava2s.  co m
    JFreeChart chart = ChartFactory.createPieChart("Total Vaccines Distributed", pieDataset, true, true, true);
    PiePlot p = (PiePlot) chart.getPlot();
    ChartFrame frame = new ChartFrame("Total Vaccines Distributed", chart);
    frame.setVisible(true);
    frame.setSize(450, 500);

}

From source file:javanews.gui.internalframe.LinkChart.java

/**
 * Initialises the class and internal logger. Uses the supplied arguments to
 * receive data from the application and add data to the charts dynamically.
 * @param title The title of the charts on display. Whether the displayed
 *               data is for <code>new</code> or <code>old</code> links.
 *               That is whether the data is for newly discovered links or
 *               existing (old) links already stored within the database.
 * @param parent The instance of <code>COMPortClient</code> that acts as
 *                the data source for the charts.
 *///w  w  w .  j a va 2  s.c  o  m
public LinkChart(String title, COMPortClient parent) {
    super("Charts", true, true, true, true);
    super.setLayer(1);
    identifier = title.toLowerCase();
    // Obtain an instance of Logger for the class
    log = LoggerFactory.getLogger(className);
    owner = parent;
    // Setup a hashtable to hold the values for up, down and unknown link states
    Hashtable<String, Integer> linkStats = new Hashtable<String, Integer>();
    if (identifier.equals("old")) {
        this.setTitle("Recognised Link Status on " + owner.getPortName() + ":");
        // Get the current figures from the link table
        linkStats = ((LinkTable) owner.getLinkTable().getModel()).getInitialFigures();
    } else if (identifier.equals("new")) {
        this.setTitle("Discovered Link Status on " + owner.getPortName() + ":");
        linkStats = ((LinkTable) owner.getNewLinkTable().getModel()).getInitialFigures();
    } else {
        // If the identifier was set to something other than old or new then it's not right.
        log.warning("An instance of LinkChart has been created for an unknown purpose.");
        return;
    }
    // Initialise the dataset for the pie chart
    dpdCurrentData = new DefaultPieDataset();
    dpdCurrentData.insertValue(0, "Link Down", linkStats.get("down"));
    dpdCurrentData.insertValue(1, "Link Up", linkStats.get("up"));
    dpdCurrentData.insertValue(2, "Link State Unknown", linkStats.get("unknown"));
    // Initialise the dataset for the line chart
    dcdPreviousData = new DefaultCategoryDataset();
    dcdPreviousData.addValue(linkStats.get("down"), "Link Down", Calendar.getInstance().getTime().toString());
    dcdPreviousData.addValue(linkStats.get("up"), "Link Up", Calendar.getInstance().getTime().toString());
    dcdPreviousData.addValue(linkStats.get("unknown"), "Link State Unknown",
            Calendar.getInstance().getTime().toString());
    // Set the variables we need for holding the charts
    JFreeChart jfcCurrentStatus; // This will be displayed as a pie chart
    JFreeChart jfcPreviousStatus; // This will be displayed as a line chart
    ChartPanel cpCurrent; // Chartpanels hold the JFreeChart
    ChartPanel cpPrevious;
    // Use the factory to create the charts
    jfcCurrentStatus = ChartFactory.createPieChart("Current Status", dpdCurrentData, true, true, false);
    jfcPreviousStatus = ChartFactory.createLineChart("Previous Status", "Time received", "Number of Links",
            dcdPreviousData, PlotOrientation.VERTICAL, true, true, false);
    // Add them to the chart panels
    cpCurrent = new ChartPanel(jfcCurrentStatus);
    cpPrevious = new ChartPanel(jfcPreviousStatus);
    // Add the chart panels to the content pane
    this.add(cpCurrent, BorderLayout.EAST);
    this.add(cpPrevious, BorderLayout.WEST);
    // Change the layout to show them next to each other
    this.setLayout(new GridLayout(1, 2));
    // Add a listener to the window
    this.addInternalFrameListener(new CloseLinkChart(this));
    log.finest("Adding frame to the desktop");
    // Set the window properties and display it
    Client.getJNWindow().addToDesktop(this);
    this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    this.setSize(650, 400);
    this.setVisible(true);
    owner.addChartWindow(title, this);
}

From source file:UserInterface.CDC.VARESCityReportingJPanel.java

private void viewChartjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewChartjButtonActionPerformed
    // TODO add your handling code here:

    DefaultPieDataset pieDataset = new DefaultPieDataset();
    for (CityNetwork city : state.getCityList()) {
        pieDataset.setValue(city.getName(), city.getTotalFailedVaccinesInCity());

    }/*from w  ww .ja v a  2s.  c om*/
    JFreeChart chart = ChartFactory.createPieChart("Total Failed Vaccines", pieDataset, true, true, true);
    PiePlot p = (PiePlot) chart.getPlot();
    ChartFrame frame = new ChartFrame("Total Failed Vaccines", chart);
    frame.setVisible(true);
    frame.setSize(450, 500);
}

From source file:simx.profiler.info.actor.ActorInstanceInfoTopComponent.java

/**
 * This method creates a pie chart and adds it to the target panel.
 * /*www  .java 2s  . c  o m*/
 * @param data The data set that should be visualized by the pie chart.
 * @param targetPanel The panel where the pie chart should be added to.
 */
private void createPieChart(final DefaultPieDataset data, final javax.swing.JPanel targetPanel) {
    if (data == null)
        throw new IllegalArgumentException("The parameter 'data' must not be 'null'!");
    if (targetPanel == null)
        throw new IllegalArgumentException("The parameter 'targetPanel' must not be 'null'!");

    data.setValue("???", 100);
    final JFreeChart chart = ChartFactory.createPieChart("", data, false, false, false);
    final PiePlot plot = (PiePlot) chart.getPlot();
    plot.setDirection(Rotation.CLOCKWISE);
    plot.setForegroundAlpha(0.5f);
    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(261, 157));
    targetPanel.setLayout(new BorderLayout());
    targetPanel.add(chartPanel, BorderLayout.CENTER);
}

From source file:org.dcm4chee.dashboard.ui.report.display.DisplayReportDiagramPanel.java

@Override
public void onBeforeRender() {
    super.onBeforeRender();

    Connection jdbcConnection = null;
    try {/*from   www .  j a  v a2 s  .co m*/
        if (report == null)
            throw new Exception("No report given to render diagram");

        jdbcConnection = DatabaseUtils.getDatabaseConnection(report.getDataSource());
        ResultSet resultSet = DatabaseUtils.getResultSet(jdbcConnection, report.getStatement(), parameters);

        ResultSetMetaData metaData = resultSet.getMetaData();
        JFreeChart chart = null;
        resultSet.beforeFirst();

        // Line chart - 1 numeric value
        if (report.getDiagram() == 0) {
            if (metaData.getColumnCount() != 1)
                throw new Exception(
                        new ResourceModel("dashboard.report.reportdiagram.image.render.error.1numvalues")
                                .wrapOnAssignment(this).getObject());

            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            while (resultSet.next())
                dataset.addValue(resultSet.getDouble(1), metaData.getColumnName(1),
                        String.valueOf(resultSet.getRow()));

            chart = ChartFactory.createLineChart(
                    new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this)
                            .getObject(),
                    new ResourceModel("dashboard.report.reportdiagram.image.row-label").wrapOnAssignment(this)
                            .getObject(),
                    metaData.getColumnName(1), dataset, PlotOrientation.VERTICAL, true, true, true);

            // XY Series chart - 2 numeric values
        } else if (report.getDiagram() == 1) {
            if (metaData.getColumnCount() != 2)
                throw new Exception(
                        new ResourceModel("dashboard.report.reportdiagram.image.render.error.2numvalues")
                                .wrapOnAssignment(this).getObject());

            XYSeries series = new XYSeries(metaData.getColumnName(1) + " / " + metaData.getColumnName(2));
            while (resultSet.next())
                series.add(resultSet.getDouble(1), resultSet.getDouble(2));

            chart = ChartFactory.createXYLineChart(
                    new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this)
                            .getObject(),
                    metaData.getColumnName(1), metaData.getColumnName(2), new XYSeriesCollection(series),
                    PlotOrientation.VERTICAL, true, true, true);

            // Category chart - 1 numeric value, 1 comparable value
        } else if (report.getDiagram() == 2) {
            if (metaData.getColumnCount() != 2)
                throw new Exception(
                        new ResourceModel("dashboard.report.reportdiagram.image.render.error.2values")
                                .wrapOnAssignment(this).getObject());

            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            while (resultSet.next())
                dataset.setValue(resultSet.getDouble(1),
                        metaData.getColumnName(1) + " / " + metaData.getColumnName(2), resultSet.getString(2));

            chart = new JFreeChart(
                    new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this)
                            .getObject(),
                    new CategoryPlot(dataset, new LabelAdaptingCategoryAxis(14, metaData.getColumnName(2)),
                            new NumberAxis(metaData.getColumnName(1)), new CategoryStepRenderer(true)));

            // Pie chart - 1 numeric value, 1 comparable value (used as category)
        } else if ((report.getDiagram() == 3) || (report.getDiagram() == 4)) {
            if (metaData.getColumnCount() != 2)
                throw new Exception(
                        new ResourceModel("dashboard.report.reportdiagram.image.render.error.2values")
                                .wrapOnAssignment(this).getObject());

            DefaultPieDataset dataset = new DefaultPieDataset();
            while (resultSet.next())
                dataset.setValue(resultSet.getString(2), resultSet.getDouble(1));

            if (report.getDiagram() == 3)
                // Pie chart 2D
                chart = ChartFactory
                        .createPieChart(new ResourceModel("dashboard.report.reportdiagram.image.label")
                                .wrapOnAssignment(this).getObject(), dataset, true, true, true);
            else if (report.getDiagram() == 4) {
                // Pie chart 3D
                chart = ChartFactory
                        .createPieChart3D(new ResourceModel("dashboard.report.reportdiagram.image.label")
                                .wrapOnAssignment(this).getObject(), dataset, true, true, true);
                ((PiePlot3D) chart.getPlot()).setForegroundAlpha(
                        Float.valueOf(new ResourceModel("dashboard.report.reportdiagram.image.alpha")
                                .wrapOnAssignment(this).getObject()));
            }

            // Bar chart - 1 numeric value, 2 comparable values (used as category, series)
        } else if (report.getDiagram() == 5) {
            if ((metaData.getColumnCount() != 2) && (metaData.getColumnCount() != 3))
                throw new Exception(
                        new ResourceModel("dashboard.report.reportdiagram.image.render.error.3values")
                                .wrapOnAssignment(this).getObject());

            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            while (resultSet.next())
                dataset.setValue(resultSet.getDouble(1), resultSet.getString(2),
                        resultSet.getString(metaData.getColumnCount()));

            chart = ChartFactory.createBarChart(
                    new ResourceModel("dashboard.report.reportdiagram.image.label").wrapOnAssignment(this)
                            .getObject(),
                    metaData.getColumnName(2), metaData.getColumnName(1), dataset, PlotOrientation.VERTICAL,
                    true, true, true);
        }

        int[] winSize = DashboardCfgDelegate.getInstance().getWindowSize("reportDiagramImage");
        addOrReplace(new JFreeChartImage("diagram", chart, winSize[0], winSize[1]));

        final JFreeChart downloadableChart = chart;
        addOrReplace(new Link<Object>("diagram-download") {

            private static final long serialVersionUID = 1L;

            @Override
            public void onClick() {

                RequestCycle.get().setRequestTarget(new IRequestTarget() {

                    public void respond(RequestCycle requestCycle) {

                        WebResponse wr = (WebResponse) requestCycle.getResponse();
                        wr.setContentType("image/png");
                        wr.setHeader("content-disposition", "attachment;filename=diagram.png");

                        OutputStream os = wr.getOutputStream();
                        try {
                            ImageIO.write(downloadableChart.createBufferedImage(800, 600), "png", os);
                            os.close();
                        } catch (IOException e) {
                            log.error(this.getClass().toString() + ": " + "respond: " + e.getMessage());
                            log.debug("Exception: ", e);
                        }
                        wr.close();
                    }

                    @Override
                    public void detach(RequestCycle arg0) {
                    }
                });
            }
        }.add(new Image("diagram-download-image", ImageManager.IMAGE_DASHBOARD_REPORT_DOWNLOAD)
                .add(new ImageSizeBehaviour())
                .add(new TooltipBehaviour("dashboard.report.reportdiagram.", "image.downloadlink"))));

        addOrReplace(new Image("diagram-print-image", ImageManager.IMAGE_DASHBOARD_REPORT_PRINT)
                .add(new ImageSizeBehaviour())
                .add(new TooltipBehaviour("dashboard.report.reportdiagram.", "image.printbutton")));

        addOrReplace(new Label("error-message", "").setVisible(false));
        addOrReplace(new Label("error-reason", "").setVisible(false));
    } catch (Exception e) {
        log.error("Exception: " + e.getMessage());

        addOrReplace(((DynamicDisplayPage) this.getPage()).new PlaceholderLink("diagram-download")
                .setVisible(false));
        addOrReplace(new Image("diagram-print-image").setVisible(false));
        addOrReplace(new Image("diagram").setVisible(false));
        addOrReplace(new Label("error-message",
                new ResourceModel("dashboard.report.reportdiagram.statement.error").wrapOnAssignment(this)
                        .getObject())
                                .add(new AttributeModifier("class", true, new Model<String>("message-error"))));
        addOrReplace(new Label("error-reason", e.getMessage())
                .add(new AttributeModifier("class", true, new Model<String>("message-error"))));
        log.debug(getClass() + ": ", e);
    } finally {
        try {
            jdbcConnection.close();
        } catch (Exception ignore) {
        }
    }
}

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

/**
 * Generate memory statistics/* w w w. j a  va2  s . c  o m*/
 * http://casidiablo.net/capturar-informacion-sistema-operativo-java/
 */
public JFreeChart osMemStats() throws IOException, ServletException {
    DefaultPieDataset dataset = new DefaultPieDataset();
    Sigar sigar = new Sigar();
    String title = null;

    try {
        Mem mem = sigar.getMem();
        long max = mem.getRam();
        long available = mem.getFree();
        long total = mem.getTotal();
        long used = mem.getUsed();
        long free = mem.getFree();
        title = "OS memory: " + FormatUtil.formatSize(total);

        log.debug("OS maximun memory: {}", FormatUtil.formatSize(max));
        log.debug("OS available memory: {}", FormatUtil.formatSize(available));
        log.debug("OS free memory: {}", FormatUtil.formatSize(free));
        log.debug("OS used memory: {}", FormatUtil.formatSize(used));
        log.debug("OS total memory: {}", FormatUtil.formatSize(total));

        dataset.setValue("Available (" + FormatUtil.formatSize(free) + ")", free * 100 / total);
        dataset.setValue("Used (" + FormatUtil.formatSize(used) + ")", used * 100 / total);
    } catch (SigarException se) {
        title = "OS memory: " + se.getMessage();
    } catch (UnsatisfiedLinkError ule) {
        title = "OS memory: (missing native libraries)";
    }

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

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

/**
 * Create our controls for the UI panel.
 *///from ww w  .  j a  v  a  2 s  . c  om
@Override
protected Control createControl(Composite parent) {
    Composite top = new Composite(parent, SWT.NONE);
    top.setLayout(new GridLayout(1, false));
    top.setLayoutData(new GridData(GridData.FILL_BOTH));

    Composite buttons = new Composite(top, SWT.NONE);
    buttons.setLayout(new RowLayout());

    mDisplayMode = new Combo(buttons, SWT.PUSH);
    for (String mode : CAPTIONS) {
        mDisplayMode.add(mode);
    }
    mDisplayMode.select(mMode);
    mDisplayMode.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            mMode = mDisplayMode.getSelectionIndex();
            if (mDataFile != null) {
                generateDataset(mDataFile);
            } else if (getCurrentDevice() != null) {
                loadFromDevice();
            }
        }
    });

    final Button loadButton = new Button(buttons, SWT.PUSH);
    loadButton.setText("Load from File");
    loadButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            FileDialog fileDialog = new FileDialog(loadButton.getShell(), SWT.OPEN);
            fileDialog.setText("Load bugreport");
            String filename = fileDialog.open();
            if (filename != null) {
                mDataFile = new File(filename);
                generateDataset(mDataFile);
            }
        }
    });

    mFetchButton = new Button(buttons, SWT.PUSH);
    mFetchButton.setText("Update from Device");
    mFetchButton.setEnabled(false);
    mFetchButton.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            loadFromDevice();
        }
    });

    mLabel = new Label(top, SWT.NONE);
    mLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

    mDataset = new DefaultPieDataset();
    JFreeChart chart = ChartFactory.createPieChart("", mDataset, false
    /* legend */, true/* tooltips */, false /* urls */);

    ChartComposite chartComposite = new ChartComposite(top, SWT.BORDER, chart, ChartComposite.DEFAULT_HEIGHT,
            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);
    chartComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
    return top;
}