【问题标题】:Percentage Accuracy issue in JFreeChart Pie-chartJFreeChart 饼图中的百分比精度问题
【发布时间】:2018-09-13 12:49:17
【问题描述】:

我正在使用JFreeChart 库的饼图来满足我的需要。
我想在饼图中显示百分比和总值。所以,我通过谷歌搜索。我找到了@trashgod 回答的this solution

现在根据他给出的答案,我创建了如下类:

import java.awt.Color;
import java.awt.Dimension;
import java.text.DecimalFormat;

import javax.swing.JFrame;

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;

public class TestPieChart {
    private static final String KEY1 = "Datum 1";
    public static final String KEY2 = "Datum 2";

    public static void main(String[] args) {
        DefaultPieDataset dataset = new DefaultPieDataset();
        dataset.setValue(KEY1, 45045); //49
        dataset.setValue(KEY2, 53955); //151

        JFreeChart someChart = ChartFactory.createPieChart(
            "Header", dataset, true, true, false);
        PiePlot plot = (PiePlot) someChart.getPlot();
        plot.setSectionPaint(KEY1, Color.green);
        plot.setSectionPaint(KEY2, Color.red);
        plot.setExplodePercent(KEY1, 0.10);
        plot.setSimpleLabels(true);

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

        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new ChartPanel(someChart) {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(400, 300);
            }
        });
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);

    }
}

它给出的输出如下:

55%46%的百分比,Total为101%
(因为两者都取上限值如 54.5 然后 55)

但同时,如果我将 KEY1 的值为 49,KEY2 的值为 151,那么它给出的准确结果如下:
(总和在这种情况下两者都是 100%)

所以,我的问题是:为什么 JFreeChart 对不同的值表现不同?
有没有办法解决这个问题(总百分比不会超过 100)?

【问题讨论】:

    标签: java jfreechart


    【解决方案1】:

    标签生成器的抽象父代执行的百分比计算,见here,和格式化程序的默认舍入,讨论here,都是正确的。如果需要,您可以通过在构造StandardPieSectionLabelGenerator 时指定不同的percentFormat 来更改显示 百分比的精度:

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

    注意45.5% + 54.5% = 100%

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2013-07-04
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多