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

时间:2017-05-13 23:39:03

标签: chart.js

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

作为一个更多的背景,我在条形图的顶部有一个折线图:

  • 我的条形数据是数字(以百万计,需要舍入和截断)。
  • 示例: 22345343 需要在工具提示中显示为 22M
  • 我的行数据是货币
  • 示例: 146.36534 需要在tooptip中显示为 $ 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;
                                });
                    }
                }
            }

3 个答案:

答案 0 :(得分: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';
        }
    }
}

<强>ᴅᴇᴍᴏ

&#13;
&#13;
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"
            }]
        }
    }
});
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分: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;
                }
              }
            }
          }
        };

答案 2 :(得分:0)

谢谢,G! 但是由于我可以混合我的数据集,所以最好使用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";
                        }
                    }
                }
            }
相关问题