【问题标题】:jfree chart custom labeljfree 图表自定义标签
【发布时间】:2016-04-22 10:00:37
【问题描述】:

我想在我的饼图中个性化我的数据标签,因为在我的图例中我看到 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();
}

我的饼图是这样的:

【问题讨论】:

    标签: java jfreechart


    【解决方案1】:

    如果您没有实现createDataset(),我猜问题出在key 传递给您的setValue()setValue() 方法上。而是使用MessageFormat 符号{1} 来构造自定义StandardPieSectionLabelGenerator,如图here 所示。

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

    然后,您可以从 createDataset() 的实现中删除不需要的字符,以将它们排除在您调用 ChartFactory.createPieChart() 时请求的 legend 之外。

    【讨论】:

    • 很高兴为您提供帮助;今后,您可以点击左侧的empty check mark 接受此答案。
    • 另外,可以点击一个部分并查看另一个图表(例如 LineChart)以查看更多详细信息吗?
    • 是的,为example添加一个ChartMouseListener
    • 我不明白这个方法怎么用,我放在creathechart()中,但是如何将饼图的一个部分的点击链接到一个折线图中的细节?
    • 我会在相邻的图表面板上拨打ChartMouseListener 电话setChart();如果您发布有关此主题的问题,请联系我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多