簡體   English   中英

帶有包含值的chartjs的堆疊條形圖

[英]Stacked bar chart with chartjs with included values

我正在嘗試創建一個包含值的訪問者條形圖,例如:

我想顯示每日總訪問量的條形圖,該條形圖應包含總訪問者首次訪問者的信息

因此,條形圖的數據應如下所示:

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
    }]
}

我查看了chartjs文檔,但只找到了帶有堆疊值的示例,並且該解決方案未應用於我想要的設計,有人可以參考文檔/文章/教程或個人經驗,或者我應該切換到 d3js? 謝謝。

您可以定義兩個數據集,第一個包含新訪問者的值,第二個包含所有訪問者的值。

然后您將 x 軸定義為堆疊:

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

請看下面的可運行代碼片段,看看它是如何工作的:

 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