我正在使用Chart.js在我的网站上显示数据,并希望在数据字段后缀一个后缀,以表示它们的单位是克(g)。我在文档中找不到任何有帮助的东西,但这似乎是一个非常简单的功能。
例如,我想确保数据显示为32g,38g,53g,而不只是32、38、53。您不能简单地将其添加到数组中,因为这是数字,仅用于生成图表。
PHP
$myChart = array(
"type" => "doughnut",
"data" => array(
"labels" => ['Label1', 'Label2', 'Label3'],
"datasets" => [
array(
"data" => [ 32, 38, 53 ],
)
]
)
);
HTML
<div class="chart" data-charts="{"type":"doughnut","data":{"labels":["Label1","Label2","Label3"],"datasets":[{"data":["56","31","21"],}]}}">
<div class="chart-container">
<canvas class="chartjs-render-monitor">
</canvas>
</div>
</div>
JQUERY
// Chart init
window.onload = function() {
// Find all charts
var containers = document.querySelectorAll('.chart');
// For each chart
containers.forEach(function(container) {
// Parse data
var charts = JSON.parse(container.dataset.charts);
// Add container div
var div = document.createElement('div');
div.classList.add('chart-container');
// Add canvas for chart to be drawn in
var canvas = document.createElement('canvas');
// Append new elements
div.appendChild(canvas);
container.appendChild(div);
// Config
var ctx = canvas.getContext('2d');
var config = charts;
// Init chart
var myChart = new Chart(ctx, config);
});
};
答案 0 :(得分:1)
要执行此操作,可以使用工具提示配置的回调将字符串附加到数据集中的值,如下所示:
var containers = document.querySelectorAll('.chart');
containers.forEach(function(container) {
var charts = JSON.parse(container.dataset.charts);
var div = document.createElement('div');
div.classList.add('chart-container');
var canvas = document.createElement('canvas');
div.appendChild(canvas);
container.appendChild(div);
var ctx = canvas.getContext('2d');
var config = charts;
var myChart = new Chart(ctx, $.extend(config, {
options: {
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function(tooltipItems, data) {
return data.datasets[0].data[tooltipItems.index] + 'g';
}
}
}
}
}));
});
canvas {
background-color: #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<div class="chart" data-charts='{"type":"doughnut","data":{"labels":["Label1","Label2","Label3"],"datasets":[{"data":["56","31","21"]}]}}'></div>