个性化阅读
专注于IT技术分析

JFreeChart-饼图

本文概述

饼图是一个圆形图, 分为多个扇区, 其中每个扇区的面积代表数据的大小。

下图显示了JFreeChart库中包含的饼图的一些演示版本:

饼图演示1:

JFreeChart饼图演示1

饼图演示2:

JFreeChart饼图演示2

饼图演示4:

饼图示例

让我们考虑一个类的标记分布的样本数据。

标记范围 学生人数
80-100 120
60-79 80
40-59 20
20-39 7
0-19 3

以下代码根据上述示例数据创建一个饼图:

PieChartExample.java

import java.text.DecimalFormat;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.PieSectionLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
public class PieChartExample extends JFrame {
  private static final long serialVersionUID = 6294689542092367723L;

  public PieChartExample(String title) {
    super(title);

    // Create dataset
    PieDataset dataset = createDataset();

    // Create chart
    JFreeChart chart = ChartFactory.createPieChart(
        "Pie Chart Example", dataset, true, true, false);

    //Format Label
    PieSectionLabelGenerator labelGenerator = new StandardPieSectionLabelGenerator(
        "Marks {0} : ({2})", new DecimalFormat("0"), new DecimalFormat("0%"));
    ((PiePlot) chart.getPlot()).setLabelGenerator(labelGenerator);
    
    // Create Panel
    ChartPanel panel = new ChartPanel(chart);
    setContentPane(panel);
  }

  private PieDataset createDataset() {

    DefaultPieDataset dataset=new DefaultPieDataset();
    dataset.setValue("80-100", 120);
    dataset.setValue("60-79", 80);
    dataset.setValue("40-59", 20);
    dataset.setValue("20-39", 7);
    dataset.setValue("0-19", 3);
    return dataset;
  }

  public static void main(String[] args) {
    SwingUtilities.invokeLater(() -> {
      PieChartExample example = new PieChartExample(?Pie Chart Example?);
      example.setSize(800, 400);
      example.setLocationRelativeTo(null);
      example.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      example.setVisible(true);
    });
  }
}

输出:

JFreeChart饼图示例
赞(0)
未经允许不得转载:srcmini » JFreeChart-饼图

评论 抢沙发

评论前必须登录!