简体   繁体   中英

Stacked bar chart with chartjs with included values

I am trying to create a visitors bar chart with included values, for example:

I want to show a bar chart of total daily visitors , and that bar should contain info of total visitors and first time visitors .

so data for a bar should look like:

data: {
    labels: getDataAttributes(data, 'data-date'),
    // an array holding the date of each bar (custom function)
    // for example purposes lets say its just 3 bars
    
    datasets: [{
        label: ['Number of visitors', 'Number of new visitors'],
        data: [[20,15], [25,10], [30, 15]],
        // Here if we would use a simple stacked bar chart the height would be the sum of 2 values
        // e.g.(20+15=35), but I wish that the bar height would be the number of total visitors 20
        // the tooltip should contain values of total visitors and new visitors respectively 20 and 15
    }]
}

I looked in the chartjs documentation, but found only examples with stacked values and that solution is not applied in my desired design, can someone please reference documentation/articles/tutorials or personal experience or perhaps I should switch to d3js? Thanks.

You could define two datasets, the first one would contain the values of new visitors, the second one the values of all visitors.

Then you would define the x-axis as being stacked:

options: {
  scales: {
    xAxes: [{
      stacked: true
    }],

Please take a look at below runnable code snippet to see how it works:

 const baseData = [[20,15], [25,10], [30, 15]]; new Chart('chart', { type: 'bar', data: { labels: ['25.10.2020', '26.10.2020', '27.10.2020'], datasets: [{ label: 'Number of new visitors', data: baseData.map(v => v[1]), backgroundColor: 'green' }, { label: 'Number of visitors', data: baseData.map(v => v[0]), backgroundColor: 'blue' }] }, options: { scales: { xAxes: [{ stacked: true }], yAxes: [{ ticks: { beginAtZero: true } }] } } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script> <canvas id="chart" height="100"></canvas>

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