JFreeChart:条形图 X 轴标签与大型数据集重叠

JFreeChart: Bar chart X axis labels overlapping with large datasets

我在使用 JFreeChart 创建具有相对较大数据集的条形图时遇到以下问题:

使用重叠的 X 轴标签生成的条形图。我试过将标签垂直放置,但仍然无济于事。请提供解决此问题的最佳方法。代码片段如下:

CategoryDataset categoryDataSet = getBarDataset();
JFreeChart barChart = ChartFactory.createBarChart("TITLE", "X-LABEL","Y-LABEL", categoryDataSet, PlotOrientation.VERTICAL, true, true, false);
barChart.getCategoryPlot().getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_90);
barChart.getCategoryPlot().getDomainAxis().setMaximumCategoryLabelLines(4);
jpg = Image.getInstance(im, null);
document.add(jpg);

更新: 根据@trashgod 的建议,我使用了从 0 到列数的 SlidingCategoryDataset 索引。当列数很大(此处为 50)时,X-Label 会重叠。当列数设置为较低的数字时,它工作正常。我想找到大列大小的解决方案。重要的是,我需要将图表图像导出为 pdf。请帮助我找到一个可行的解决方案。谢谢!

    private static void createBarChart() throws DocumentException, IOException {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FILE_LOCN));
        writer.setStrictImageSequence(true);
        document.open();
        CategoryDataset categoryDataset = createDataset();
        int colCount = categoryDataset.getColumnCount();
        SlidingCategoryDataset slidingCategoryDataSet = new SlidingCategoryDataset(categoryDataset, 0, colCount);
        JFreeChart barChart = ChartFactory.createBarChart("TITLE", "X-LABEL","Y-LABEL", slidingCategoryDataSet, 
                PlotOrientation.VERTICAL, true, true, false);
        barChart.getCategoryPlot().getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_90);
        barChart.getCategoryPlot().getDomainAxis().setMaximumCategoryLabelLines(4);
        java.awt.Image im = barChart.createBufferedImage(400, 400);
        Image jpg = Image.getInstance(im, null);
        jpg.scaleToFit(400, 400);
        document.add(jpg);
        document.close();
        writer.close();
    }

    private static CategoryDataset createDataset() {
        DefaultCategoryDataset dataset = new DefaultCategoryDataset();
        for (int i = 0; i <= 50; i++) {
            dataset.addValue(i, "R", "C" + i);
        }
        return dataset;
    }

分类较多时,支持setCategoryLabelPositions() is a good choice for maximizing legibility. Arbitrary CategoryLabelPositions指定竖向标签

在交互式图表中,SlidingCategoryDataset, mentioned here, allows your application to set the count and starting index of visible categories as desired, perhaps using a slider or spinner, as shown here

How can I achieve this in a PDF?…More pixels seems a good idea, but how can we implement that here?

在具有给定数量的类别的固定大小的上下文中,您可以通过 createBufferedImage(), as shown here, or Image.scaleToFit() 优化图表图像的大小。对于更大的数据集,可以以特定领域的方式创建多个链接图表,例如按年份或子公司。