Chartjs v2 - 多个数据集的格式工具提示(条形和直线)

问题描述 投票:10回答:3

阅读了很多关于如何使用工具提示回调格式​​化ChartJS v2.x中的工具提示的内容。到目前为止我已经取得了成功,但发现我无法为我拥有的两个数据集定义两种不同的格式。

作为一个更多的上下文,我有一个折叠在条形图顶部的折线图:

  • 我的条形数据是数字的(以百万计,需要舍入和截断)。
  • 示例:22345343需要在工具提示中显示为22M

  • 我的行数据是一种货币
  • 示例:146.36534需要在工具提示中显示为$ 146.37

到目前为止,这是我的简短WIP代码。这会将工具提示格式化为圆形并包含$符号。如何扩展它以便我可以在工具提示中单独格式化条形数据?


tooltips: {
                mode: 'index',
                intersect: false,
                callbacks: {
                    label: function(tooltipItem, data) {
                        return "$" + Number(tooltipItem.yLabel).toFixed(2).replace(/./g, function(c, i, a) {
                                    return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
                                });
                    }
                }
            }
chart.js
3个回答
16
投票

您可以使用以下工具提示回调函数来实现...

callbacks: {
    label: function (t, d) {
        if (t.datasetIndex === 0) {
            return '$' + t.yLabel.toFixed(2)
        } else if (t.datasetIndex === 1) {
            return Math.round(+t.yLabel.toString().replace(/(\d{2})(.*)/, '$1.$2')) + 'M';
        }
    }
}

ᴅᴇᴍᴏ

var ctx = document.getElementById("canvas").getContext("2d");
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ["January", "February", "March", "April", "May"],
        datasets: [{
            type: 'line',
            label: "Sales",
            data: [144.36534, 146.42534, 145.23534, 147.19534, 145],
            fill: false,
            borderColor: '#EC932F',
            backgroundColor: '#EC932F',
            tension: 0,
            yAxisID: 'y-axis-2'
        }, {
            type: 'bar',
            label: "Visitor",
            data: [22345343, 23345343, 24345343, 25345343, 230245343],
            backgroundColor: '#71B37C',
            yAxisID: 'y-axis-1'
        }]
    },
    options: {
        responsive: false,
        tooltips: {
            mode: 'index',
            intersect: false,
            callbacks: {
                label: function (t, d) {
                    if (t.datasetIndex === 0) {
                        return '$' + t.yLabel.toFixed(2);
                    } else if (t.datasetIndex === 1) {
                        if (t.yLabel.toString().length === 9) {
                            return Math.round(+t.yLabel.toString().replace(/(\d{3})(.*)/, '$1.$2')) + 'M';
                        } else return Math.round(+t.yLabel.toString().replace(/(\d{2})(.*)/, '$1.$2')) + 'M';
                    }
                }
            }
        },
        scales: {
            yAxes: [{
                id: "y-axis-1",
                position: "left"
            }, {
                id: "y-axis-2",
                position: "right"
            }]
        }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="canvas" width="400" height="190"></canvas>

1
投票

尝试使用以下代码!

   let  DoughnutForSavingCount = {
        labels: [
          intl.formatMessage({ id: 'Guarantee' }),
          intl.formatMessage({ id: 'ILAS' }),
          intl.formatMessage({ id: 'No Idea' })
        ],

        datasets: [
          /* Outer doughnut data starts*/

          {
            label: 'Graph1',
            data: [
              _.get(getClientSavingILASPolicyData[0], 'countwithGuaranttee') >
                0 &&
              _.get(getClientSavingILASPolicyData[0], 'totalWithGuarantee') ===
                0
                ? 0.1
                : _.get(getClientSavingILASPolicyData[0], 'totalWithGuarantee'),
              _.get(getClientSavingILASPolicyData[0], 'countwithILAS', 0) > 0 &&
              _.get(getClientSavingILASPolicyData[0], 'totalWithILAS') === 0
                ? 0.1
                : _.get(getClientSavingILASPolicyData[0], 'totalWithILAS'),
              _.get(getClientSavingILASPolicyData[0], 'countNoIdea', 0) > 0 &&
              _.get(getClientSavingILASPolicyData[0], 'totalWithNoIdea') === 0
                ? 0.1
                : _.get(getClientSavingILASPolicyData[0], 'totalWithNoIdea')
            ],
            backgroundColor: ['#8c1aff', '#BF80FF', '#E9e9e9'],
            hoverBackgroundColor: ['#8c1aff', '#BF80FF', '#E9e9e9']
          },
          /* Outer doughnut data ends*/

          /* Inner doughnut data starts*/
          {
            label: 'Graph2',
            data: [
              _.get(getClientSavingILASPolicyData[0], 'countwithGuaranttee'),
              _.get(getClientSavingILASPolicyData[0], 'countwithILAS'),
              _.get(getClientSavingILASPolicyData[0], 'countNoIdea')
            ],
            backgroundColor: ['#8c1aff', '#BF80FF', '#E9e9e9'],
            hoverBackgroundColor: ['#8c1aff', '#BF80FF', '#E9e9e9']
          }
          /* Inner doughnut data ends*/
        ],
        borderWidth: [1]
      };



     let DoughnutForSavingCountConfig = {
          cutoutPercentage: 70,
          legend: {
            display: true,
            position: 'bottom',
            labels: {
              fontColor: '#34A0DC',
              fontSize: 10,
              fontFamily: 'Helvetica',
              boxWidth: 10,
              usePointStyle: true
            }
          },
          responsive: true,
          plugins: {
            datalabels: {
              display: false
            }
          },
          tooltips: {
            enabled: true,
            //*****add for reference********** */
            callbacks: {
              label: function(tooltipItems, data) {
                if (tooltipItems.datasetIndex) {
                  var label = data.labels[tooltipItems.index] || '';
                  var currentValue =
                    data.datasets[tooltipItems.datasetIndex].data[
                      tooltipItems.index
                    ];
                  if (label) {
                    label += ': ';
                  }
                  label += currentValue == '0.1' ? '0' : currentValue;
                  return label;
                } else {
                  var label = data.labels[tooltipItems.index] || '';
                  var currentValue =
                    data.datasets[tooltipItems.datasetIndex].data[
                      tooltipItems.index
                    ];
                  if (label) {
                    label += ': ';
                  }
                  label += intl.formatMessage({ id: 'HKD' }) + ' ';
                  label +=
                    currentValue == '0.1'
                      ? '0'
                      : currentValue
                          .toString()
                          .replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                  return label;
                }
              }
            }
          }
        };

0
投票

谢谢,GRUNT!但由于我的数据集可以混合使用,因此最好使用yAxisID来检查正确的数据集。

            tooltips: {
                callbacks: {
                    label: function (tooltipItem, details) {
                        if (details.datasets[tooltipItem.datasetIndex].yAxisID == "$") {
                            let dataset = details.datasets[tooltipItem.datasetIndex];
                            let currentValue = dataset.data[tooltipItem.index];
                            return dataset.label + ": " + currentValue.toFixed(2) + " $";
                        } else {
                            let dataset = details.datasets[tooltipItem.datasetIndex];
                            let currentValue = dataset.data[tooltipItem.index];
                            return dataset.label + ": " + currentValue +" pieces";
                        }
                    }
                }
            }
© www.soinside.com 2019 - 2024. All rights reserved.