Chart.js:甜甜圈中间的千位分隔符和标题

阿农·罗德里格斯(Arnon Rodrigues)

我进行了很多搜索,并在工具提示中添加了千位分隔符。但是我想让它在任何有文字的地方都可以使用。我居住的地方使用“。” 分隔千位和“,”代表小数。

我没有找到一种简单的方法将标题放在甜甜圈中间。

这就是我所拥有的:

Chart.defaults.global.defaultFontColor = '#7792b1';

var ctx = document.getElementById('myChart').getContext('2d');
var dataset = [{
  label: 'Volume de Operações',
  data: [254000.87, 355000.57],
  backgroundColor: ['#4bb8df', '#6290df']
}]
var chart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ['CALL', 'PUT'],
    datasets: dataset
  },

  options: {
    rotation: 1 * Math.PI,
    circumference: 1 * Math.PI,
    legend: {
      display: false
    },
    cutoutPercentage: 60,
    plugins: {
      labels: [{
        render: 'label',
        arc: true,
        fontStyle: 'bold',
        position: 'outside'
      }, {
        render: 'percentage',
        fontColor: '#ffffff',
        precision: 1
      }],
    },
    title: {
      display: true,
      fontSize: 15,
      text: [
        dataset.reduce((t, d) => t + d.data.reduce((a, b) => a + b), 0),
        'Volume Total'
      ],
      position: 'bottom'
    },
    tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
          var dataLabel = data.labels[tooltipItem.index];
          var value = ': ' + data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();
          if (Chart.helpers.isArray(dataLabel)) {
            dataLabel = dataLabel.slice();
            dataLabel[0] += value;
          } else {
            dataLabel += value;
          }
          return dataLabel;
        }
      }
    }
  }
});
<canvas id="myChart" style="max-width: 450px"></canvas>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>

简而言之:

  • 全局千位分隔符:(。)
  • 甜甜圈中间的标题
  • 无标签的工具提示:仅值
李·莱纳利

要在工具提示中不显示标题,您只需在自定义标签calback中返回值。因此,您的回调将变为:

label: function(tooltipItem, data) {
      return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();
    }

没有任何方法可以使标题位于圆圈的中间,您必须为此编写一个自定义插件。

要替换百分比标签中的千位serperator,您将必须编写一个自定义渲染器。所以改为render: 'percentage'您将获得如下内容:

// custom render
{
  render: function (args) {
    // args will be something like:
    // { label: 'Label', value: 123, percentage: 50, index: 0, dataset: {...} }
    return '$' + args.value;
  }
}

您将必须进行逻辑运算,以便将值仍然转换为百分比

编辑自定义工具提示,这样您就不会在前面看到颜色。

Chart.defaults.global.defaultFontColor = '#7792b1';

var ctx = document.getElementById('myChart').getContext('2d');
var dataset = [{
  label: 'Volume de Operações',
  data: [254000.87, 355000.57],
  backgroundColor: ['#4bb8df', '#6290df']
}]
var chart = new Chart(ctx, {
  type: 'doughnut',
  data: {
    labels: ['CALL', 'PUT'],
    datasets: dataset
  },

  options: {
    rotation: 1 * Math.PI,
    circumference: 1 * Math.PI,
    legend: {
      display: false
    },
    cutoutPercentage: 60,
    plugins: {
      labels: [{
        render: 'label',
        arc: true,
        fontStyle: 'bold',
        position: 'outside'
      }, {
        render: 'percentage',
        fontColor: '#ffffff',
        precision: 1
      }],
    },
    title: {
      display: true,
      fontSize: 15,
      text: [
        dataset.reduce((t, d) => t + d.data.reduce((a, b) => a + b), 0),
        'Volume Total'
      ],
      position: 'bottom'
    },
    tooltips: {
      enabled: false,
      custom: function(tooltipModel) {
        // Tooltip Element
        var tooltipEl = document.getElementById('chartjs-tooltip');

        // Create element on first render
        if (!tooltipEl) {
          tooltipEl = document.createElement('div');
          tooltipEl.id = 'chartjs-tooltip';
          tooltipEl.innerHTML = '<table></table>';
          document.body.appendChild(tooltipEl);
        }

        // Hide if no tooltip
        if (tooltipModel.opacity === 0) {
          tooltipEl.style.opacity = 0;
          return;
        }

        // Set caret Position
        tooltipEl.classList.remove('above', 'below', 'no-transform');
        if (tooltipModel.yAlign) {
          tooltipEl.classList.add(tooltipModel.yAlign);
        } else {
          tooltipEl.classList.add('no-transform');
        }

        function getBody(bodyItem) {
          return bodyItem.lines[0].split(': ')[1].replace('.', ',');
        }

        // Set Text
        if (tooltipModel.body) {
          var titleLines = tooltipModel.title || [];
          var bodyLines = tooltipModel.body.map(getBody);

          var innerHtml = '<thead>';
          innerHtml += '</thead><tbody>';

          bodyLines.forEach(function(body, i) {
            var colors = tooltipModel.labelColors[i];
            var style = 'background:' + colors.backgroundColor;
            style += '; border-color:' + colors.borderColor;
            style += '; border-width: 2px';
            var span = '<span style="' + style + '"></span>';
            innerHtml += '<tr><td>' + span + body + '</td></tr>';
          });
          innerHtml += '</tbody>';

          var tableRoot = tooltipEl.querySelector('table');
          tableRoot.innerHTML = innerHtml;
        }

        // `this` will be the overall tooltip
        var position = this._chart.canvas.getBoundingClientRect();

        // Display, position, and set styles for font
        tooltipEl.style.opacity = 1;
        tooltipEl.style.position = 'absolute';
        tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
        tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
        tooltipEl.style.fontFamily = tooltipModel._bodyFontFamily;
        tooltipEl.style.fontSize = tooltipModel.bodyFontSize + 'px';
        tooltipEl.style.fontStyle = tooltipModel._bodyFontStyle;
        tooltipEl.style.padding = tooltipModel.yPadding + 'px ' + tooltipModel.xPadding + 'px';
        tooltipEl.style.pointerEvents = 'none';
      }
      /*
        callbacks: {
          label: function(tooltipItem, data) {
            return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index].toLocaleString();
          },
          
        }*/
    }
  }
});
#chartjs-tooltip {
  opacity: 1;
  position: absolute;
  background: rgba(0, 0, 0, .7);
  color: white;
  border-radius: 3px;
  -webkit-transition: all .1s ease;
  transition: all .1s ease;
  pointer-events: none;
  -webkit-transform: translate(-50%, 0);
  transform: translate(-50%, 0);
}
<canvas id="myChart" style="max-width: 450px"></canvas>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>

您可能想要在工具提示中添加一些点作为千位分隔符,但这取决于您。最好的getBody方法是在方法中。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章