我想在条形图中没有数据时显示文本消息。我正在使用 react-chart-js-2
和以下代码来显示消息,但它不起作用。我不知道出了什么问题,但我认为这可能有效,因为我指的是这个 fiddle https://jsfiddle.net/x04ptfuu/
Chart.plugins.register({
afterDraw: function(chart) {
if (chart.data.datasets.length === 0) {
// No data is present
var ctx = chart.chart.ctx;
var width = chart.chart.width;
var height = chart.chart.height
chart.clear();
ctx.save();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = "16px normal 'Helvetica Nueue'";
ctx.fillText('No data to display', width / 2, height / 2);
ctx.restore();
}
}
});
我的条形图 Canvas 元素可用于 React ChartJS 2:
<Bar data={this.state.chart2Data}
height={650}
width={1200}
options={{
title: {
display: true,
text: 'Repetitive Observations - Review 2',
fontSize: 16,
fontColor: '#000000'
},
legend: {
display: true,
position: 'top',
labels: {
fontColor: '#000000'
}
},
maintainAspectRatio: false,
plugins: {
datalabels: {
display: function(context) {
return context.dataset.data[context.dataIndex] !== 0},
color: '#ffffff'
}
},
responsive: false,
scales: {
xAxes:[{
scaleLabel: {
display: true,
labelString: 'Activity',
fontStyle: 'bold',
fontColor: '#000000',
fontSize: 13
},
ticks: {
fontColor: '#000000',
minRotation: 90
}
}],
yAxes:[{
ticks: {
fontColor: '#000000'
}
}]
}
}}
/>
有人可以帮忙吗?
最佳答案
fiddle您所指的纯粹是 Javascript
。
在 React 中你有 Conditional Rendering ,
{this.state.chart2Data && this.state.chart2Data.length > 0 ? <Bar data = {this.state.chart2Data}
height = {
650
}
width = {
1200
}
options = {
{
title:
{
display: true,
text: 'Repetitive Observations - Review 2',
fontSize: 16,
fontColor: '#000000'
},
legend:
{
display: true,
position: 'top',
labels:
{
fontColor: '#000000'
}
},
maintainAspectRatio: false,
plugins:
{
datalabels:
{
display: function(context)
{
return context.dataset.data[context.dataIndex] !== 0
},
color: '#ffffff'
}
},
responsive: false,
scales:
{
xAxes: [
{
scaleLabel:
{
display: true,
labelString: 'Activity',
fontStyle: 'bold',
fontColor: '#000000',
fontSize: 13
},
ticks:
{
fontColor: '#000000',
minRotation: 90
}
}],
yAxes: [
{
ticks:
{
fontColor: '#000000'
}
}]
}
}
}
/>
:
<div> No Data to display </div>
}
关于javascript - 使用 Chart.js 在条形图中显示未找到记录消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57476104/