You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JFreeChart中绘制并列柱状的直方图?

解决JFreeChart多系列直方图柱子并列显示的问题

要实现JFreeChart中多系列直方图的柱子在同一区间(bin)内并列显示,核心是通过配置BarRenderer的参数调整柱子宽度和间距,具体操作如下:

  • 确保多系列的直方图区间(bin)参数一致,保证柱子能对齐并列
  • 配置渲染器的柱子宽度、同组间距,同时调整类别轴的区间间距

代码示例

// 构建多系列直方图数据集,确保各系列的bin数量、范围一致
HistogramDataset dataset = new HistogramDataset();
// 示例:添加两个系列,使用相同的bin参数
dataset.addSeries("系列1", dataArray1, 10, 0.0, 100.0);
dataset.addSeries("系列2", dataArray2, 10, 0.0, 100.0);

// 创建适配直方图需求的柱状图
JFreeChart chart = ChartFactory.createBarChart(
    "多系列并列直方图",
    "数值区间",
    "频数",
    dataset,
    PlotOrientation.VERTICAL,
    true, // 显示图例
    true, // 显示工具提示
    false // 不生成URL
);

// 获取绘图区与渲染器
CategoryPlot plot = (CategoryPlot) chart.getPlot();
BarRenderer renderer = (BarRenderer) plot.getRenderer();

// 设置单根柱子宽度(比如0.4,两个系列总和0.8,预留区间空隙)
renderer.setBarWidth(0.4);
// 关闭同区间内不同系列柱子的间距,让它们紧挨着并列
renderer.setItemMargin(0.0);

// 调整区间之间的间距,优化视觉效果
CategoryAxis domainAxis = (CategoryAxis) plot.getDomainAxis();
domainAxis.setCategoryMargin(0.2);

关键参数说明

  • setBarWidth:控制单根柱子的宽度,可根据系列数量调整(比如n个系列,设置为(1 - 区间间距)/n左右的值)
  • setItemMargin:设置同区间内不同系列柱子的间距,设为0可让柱子紧密并列
  • setCategoryMargin:设置不同区间之间的间距,避免区间过于拥挤

内容的提问来源于stack exchange,提问作者Brian Schack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:20:44