简体   繁体   中英

Chart js grouped bar chart with individual label

I'm trying to implement a grouped bar chart with label for each bar chart. I don't want to have second label as a legend, basically i want 2 labels: one for group and one for element in dataset. Something like: 在此处输入图像描述

Where do i need to put the second label(Male/Female), i put this label in datasets but it's not working.

Where do i need to put the second label(Male/Female), i put this label in datasets but it's not working.

You should declare and configure another x-axis. In the following example inspired by your data, I use options.scales.x.ticks.callback (see Labeling Axes | Chart.js ) which allows me to inject new labels.

 const ctx = document.getElementById('myChart'); new Chart(ctx, { type: 'bar', data: { labels: ['Category 1', 'Category 2', 'Category 3', 'Category 4'], datasets: [{ label: 'Dataset 1', data: [3, 4, 4, 2], stack: 'Stack 0' }, { label: 'Dataset 2', data: [5, 3, 4, 7], stack: 'Stack 0' }, { label: 'Dataset 3', data: [3, 0, 4, 4], stack: 'Stack 1' }, { label: 'Dataset 4', data: [2, 5, 6, 2], stack: 'Stack 1' }] }, options: { scales: { x: { stacked: true, ticks: { font: { weight: 'bold' }, callback: () => 'Label 1 | Label 2' } }, x2: { border: { display: false }, grid: { display: false } }, y: { stacked: true, beginAtZero: true } }, plugins: { legend: { display: false } } } });
 .chart-container { position: relative; width: 600px; }
 <script src="https://cdn.jsdelivr.net/npm/chart.js@4.2.0"></script> <div class="chart-container"> <canvas id="myChart"></canvas> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM