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

如何使用纯Chart.js 3.5.1实现人口年龄金字塔图表

Chart.js 3.5.1 人口年龄金字塔实现方案

实现逻辑

  • 基于水平条形图实现,将男性人口数据转为负值使其向X轴负方向渲染,女性数据保留正值向正方向渲染,形成对称的金字塔结构
  • 配置X轴刻度回调移除负号,保证两侧数值均显示为正数
  • 共用Y轴作为年龄分组维度,对齐两侧分类数据

完整实现代码

首先在项目中引入Chart.js 3.5.1版本资源,再添加如下代码:

<canvas id="agePyramid" width="800" height="600"></canvas>
// 年龄分组数据,可根据实际需求替换
const ageGroups = ['0-4岁', '5-9岁', '10-14岁', '15-19岁', '20-24岁', '25-29岁', '30-34岁', '35-39岁', '40-44岁', '45-49岁', '50-54岁', '55-59岁', '60-64岁', '65-69岁', '70-74岁', '75-79岁', '80岁+'];
// 男性数据转为负值,实现左侧展示
const maleData = [1200, 1300, 1350, 1400, 1500, 1450, 1400, 1350, 1300, 1250, 1200, 1100, 1000, 900, 700, 500, 300].map(val => -val);
// 女性数据保留正值,实现右侧展示
const femaleData = [1150, 1250, 1320, 1380, 1480, 1460, 1420, 1360, 1310, 1270, 1220, 1120, 980, 880, 720, 520, 350];

const ctx = document.getElementById('agePyramid').getContext('2d');
new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ageGroups,
    datasets: [
      {
        label: '男性',
        data: maleData,
        backgroundColor: 'rgba(54, 162, 235, 0.6)',
        borderColor: 'rgba(54, 162, 235, 1)',
        borderWidth: 1,
        barPercentage: 0.9,
        categoryPercentage: 0.8
      },
      {
        label: '女性',
        data: femaleData,
        backgroundColor: 'rgba(255, 99, 132, 0.6)',
        borderColor: 'rgba(255, 99, 132, 1)',
        borderWidth: 1,
        barPercentage: 0.9,
        categoryPercentage: 0.8
      }
    ]
  },
  options: {
    indexAxis: 'y', // 切换为横向条形图模式
    responsive: true,
    scales: {
      x: {
        stacked: true,
        // 可根据实际数据最大值调整min和max,保证两侧刻度对称
        min: -1600,
        max: 1600,
        ticks: {
          callback: function(value) {
            // 移除X轴刻度的负号,统一显示正数
            return Math.abs(value);
          }
        },
        title: {
          display: true,
          text: '人口数量'
        }
      },
      y: {
        stacked: true,
        title: {
          display: true,
          text: '年龄组'
        }
      }
    },
    plugins: {
      legend: {
        position: 'top'
      },
      tooltip: {
        callbacks: {
          label: function(context) {
            // 浮层提示中的男性数值也显示为正数
            return `${context.dataset.label}: ${Math.abs(context.parsed.x)}`;
          }
        }
      }
    }
  }
});

参数调整说明

  • 可根据实际数据的最大值调整X轴的min和max参数,保证两侧坐标轴刻度对称,展示效果更规整
  • 可自定义数据集的backgroundColor、borderColor参数调整配色,匹配设计需求
  • barPercentage和categoryPercentage参数可调整条形的宽度和分组间距
  • 代码中已统一处理X轴刻度和浮层提示的数值显示,无需额外适配负数展示问题

内容的提问来源于stack exchange,提问作者Yige Song

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 09:30:04