首页 > 解决方案 > JFreeChart 条形图类别轴偏移

问题描述

JFreeChart用来生成条形图,效果很好。数据集包含多个值,但如果数据集仅包含一个值,则条将显示在中间而不是底部:

在此处输入图像描述

我需要它显示如下:

条形图图像

以下是我用来生成条形图的代码:

double max = 200;
// Prepare the data set
DefaultCategoryDataset barDataset = new DefaultCategoryDataset();
barDataset.setValue(225, "Billed", "Dec");
//Create the chart
JFreeChart chart = ChartFactory.createBarChart(
    "", "", "", barDataset,
    PlotOrientation.HORIZONTAL, false, true, false);
ChartPanel chart3 = new ChartPanel(chart);
chart3.getChart().getPlot().setOutlinePaint(null);
(chart3.getChart().getPlot()).setBackgroundAlpha(0.0f); // setForegroundAlpha(0.5f);;
CategoryPlot plot = (CategoryPlot) chart.getPlot();
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setRange(0, max);
if (max <= 10) {
    rangeAxis.setTickUnit(new NumberTickUnit(2));
    System.out.println("tick unit 2 max " + max);
} else {
    rangeAxis.setTickUnit(new NumberTickUnit(5 * (Math.ceil(Math.abs((max / 6) / 5)))));
    System.out.println("tick unit " + (5 * (Math.ceil(Math.abs((max / 6) / 5)))) + " max " + max);
}
Font font3 = new Font("Arial Unicode MS", Font.BOLD, 22);
plot.getDomainAxis().setLabelFont(font3);
plot.getRangeAxis().setLabelFont(font3);
plot.getDomainAxis().setCategoryMargin(0.3);
Font categoryLabelFont = new Font("Arial Unicode MS", Font.BOLD, 12);
CategoryAxis categoryAxis = (CategoryAxis) plot.getDomainAxis();
categoryAxis.setTickLabelFont(categoryLabelFont);
ValueAxis valueAxis = (ValueAxis) plot.getRangeAxis();
valueAxis.setTickLabelFont(categoryLabelFont);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(new Color(192, 192, 192));
plot.setRangeGridlineStroke(new BasicStroke(1));
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setBarPainter(new StandardBarPainter());
// ajust the bar width and spacing between bars
renderer.setMaximumBarWidth(0.1);
// Spaces between bars
renderer.setItemMargin(0.1);
plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
// custom columns color
renderer.setSeriesPaint(0, new Color(0xf5, 0x8a, 0x86));
renderer.setSeriesPaint(1, new Color(0xf0, 0x56, 0x60));
ChartUtilities.saveChartAsPNG(new File(imagePath), chart, 510, 260);

标签: javabar-chartjfreechart

解决方案


推荐阅读