Looking for help: How to permanently display data labels on a chart consistent with their position
P粉302160436
2023-08-15 23:21:18
<p>I want to display these data labels permanently on the chart so that they are always visible, not just on mouseover. Can anyone help me? [Here is an example, similar to this one] I also put down my code.
(https://i.stack.imgur.com/TY8X1.png)</p>
<pre class="brush:php;toolbar:false;"><!DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>pie chart example</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<div style="position: relative;">
<canvas id="pieChart" width="400" height="400"></canvas>
</div>
<script>
// Get the canvas element
var canvas = document.getElementById('pieChart');
//Create a pie chart
var pieChart = new Chart(canvas, {
type: 'pie',
data: {
labels: ['online', 'offline'],
datasets: [{
data: [8, 2],
backgroundColor: ['rgba(71, 190, 125, 1)', 'rgba(241, 65, 108, 1)'],
borderWidth: 0
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
},
datalabels: {
color: '#fff',
anchor: 'end', // The position of the data label (start, center, end)
align: 'end', // Text alignment (start, center, end)
offset: 10, // offset between label and chart
formatter: (value, ctx) => {
let label = ctx.chart.data.labels[ctx.dataIndex];
return label ': ' value '%';
}
}
}
}
});
</script>
</body>
</html></pre>
<p><br /></p>
I added a separate container for the labels and styled them to match the chart color. I'm using flexbox to position the labels to the left of the chart. The positionLabelsContainer() function positions the label container based on the chart size and adds an event listener to reposition when the window is resized.