jfree图表自定义标签

时间:2016-04-22 10:00:37

标签: java jfreechart

我想在我的饼图中对我的数据标签进行个性化处理,因为在我的图例中我看到data = value,在标签中我看到data = value。 我怎么做只看到图例中的名称数据和标签中的值? 我绘制图表的代码是:

    public JfreeChart(String applicationTitle, String chartTitle)throws SQLException {
    super(applicationTitle);
    JFreeChart barChart = null;
    dataset=createDataset(conn,barChart);


    barChart = ChartFactory.createPieChart(chartTitle,dataset, true, true, false);
    ChartPanel chartPanel = new ChartPanel(barChart);
    PiePlot plot = new PiePlot(dataset);
    plot.setLabelFont(new Font("SansSerif", Font.PLAIN, 12));
    plot.setNoDataMessage("No data available");
    plot.setCircular(true);
    plot.setLabelGap(0.02);

    chartPanel.setPreferredSize(new java.awt.Dimension(560, 367));
    setContentPane(chartPanel);
    try {
        ChartUtilities.saveChartAsPNG(new File("directory"), barChart, 600,450);
        writeChartToPDF(barChart, 600, 450,"C:\\Users\\axs0552\\Desktop\\grafico.pdf");
    } catch (IOException ex) {
        System.out.println(ex.getLocalizedMessage());
    }
}

public static void writeChartToPDF(JFreeChart chart, int width, int height,
        String fileName) {
    PdfWriter writer = null;

    Document document = new Document();

    try {
        writer = PdfWriter.getInstance(document, new FileOutputStream(
                fileName));
        document.open();
        PdfContentByte contentByte = writer.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D graphics2d = template.createGraphics(width, height,new DefaultFontMapper());
        Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width,height);

        chart.draw(graphics2d, rectangle2d);

        graphics2d.dispose();
        contentByte.addTemplate(template, 0, 0);

    } catch (Exception e) {
        e.printStackTrace();
    }
    document.close();
}

我的饼图是这样的:

pieCart

1 个答案:

答案 0 :(得分:1)

如果没有createDataset()的实施,我猜这个问题来自key传递给setValue() DefaultPieDataset方法的问题。相反,请使用MessageFormat符号{1}构建自定义StandardPieSectionLabelGenerator,如图here所示。

PiePlot plot = (PiePlot) chart.getPlot();
PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator("{0} = {1}");
plot.setLabelGenerator(gen);

image

然后,您可以从createDataset()的实施中删除不需要的字符,使其远离legend调用中请求的ChartFactory.createPieChart()