chart.js - 如何隐藏小屏幕的 Chart.js 数据标签
问题描述
我正在尝试隐藏由小屏幕数据标签插件生成的数据标签。
我认为我可以使用 chartjs 的 onResize 属性并在宽度变小时将 display 设置为 false。这很像这里找到的隐藏标签解决方案。
不幸的是,我无法让它发挥作用。我有以下不起作用的CodePen。
var moneyFormat = wNumb({
decimals: 0,
thousand: ',',
prefix: '$',
negativeBefore: '-'
});
var percentFormat = wNumb({
decimals: 0,
suffix: '%',
negativeBefore: '-'
});
/*
* Unregister chartjs-plugins-datalabels - not really necessary for this use case
*/
Chart.plugins.unregister(ChartDataLabels);
var doughnutdata = {
labels: ['Housing',
'Food',
'Transportation',
'Clothing',
'Healthcare',
'Childcare',
'Misc'],
datasets: [
{
backgroundColor: [
'#9B2A00',
'#5B5C90',
'#6B8294',
'#1A6300',
'#BE0000',
'#B8A853',
'#64A856'
],
borderColor: [
'#FFFFFF',
'#FFFFFF',
'#FFFFFF',
'#FFFFFF',
'#FFFFFF',
'#FFFFFF',
'#FFFFFF'
],
data: [88480, 57680, 40050, 18430, 23860, 25840, 17490]
}
]
};
var chartOptions = {
responsive: true,
maintainAspectRatio: true,
legend: {
labels: {
boxWidth: 20
}
},
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
var index = tooltipItem.index;
return data.labels[index] + ': ' + moneyFormat.to(data.datasets[0].data[index]) + '';
}
}
},
plugins: {
datalabels: {
anchor: 'end',
backgroundColor: function (context) {
return context.dataset.backgroundColor;
},
borderColor: 'white',
borderRadius: 25,
borderWidth: 1,
color: 'white',
font: {
size: 10
},
formatter: function (value, pieID) {
var sum = 0;
var dataArr = pieID.chart.data.datasets[0].data;
dataArr.map(function (data) {
sum += data;
});
var percentage = percentFormat.to((value * 100 / sum));
return percentage;
}
}
}
};
var doughnutID = document.getElementById('doughnutchart').getContext('2d');
var pieChart = new Chart(doughnutID, {
plugins: [ChartDataLabels],
type: 'doughnut',
data: doughnutdata,
options: chartOptions,
onResize: function(chart, size) {
var showLabels = (size.width < 500) ? false : true;
chart.options = {
plugins: {
datalabels: {
display: showLabels
}
}
};
}
});
任何关于我做错了什么(和修复)的想法将不胜感激。
解决方案
可以使用可编写脚本的选项来实现响应性,在您的情况下,如果图表小于特定大小,您将使用一个函数作为display
返回的选项。false
(示例):
options: {
plugins: {
datalabels: {
display: function(context) {
return context.chart.width > 500;
}
}
}
}
推荐阅读
- android - 首次登录在 Android Kotlin 上抛出 401 Unaauthorized Access
- python - 带有http触发器的Python Azure函数看不到json正文
- excel - 如何截取网页截图,并将其粘贴到新电子邮件的正文中?
- amazon-web-services - 禁止在 sns:ListTopics 上使用通配符资源
- python - 那是什么类型的错误?
- excel - 连接区域中的行和区域中的列
- json - 将列表转换为 Groovy 中的地图列表
- raspberry-pi - 树莓派 pico usb 在 Windows 上调试
- javascript - 如何解决/修复此问题 throw new TypeError('app.use() requires a middleware function') 在节点 js 中启动服务器时
- python - 使用python从json中提取csfr令牌