简体   繁体   English

带有包含值的chartjs的堆叠条形图

[英]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?我查看了chartjs文档,但只找到了带有堆叠值的示例,并且该解决方案未应用于我想要的设计,有人可以参考文档/文章/教程或个人经验,或者我应该切换到 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:然后您将 x 轴定义为堆叠:

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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