带有缩放插件的Chartjs,如何设置图表上显示的限制数据



我使用Angular v13和chartjs v3,我还安装了chartjs-插件zoom,它非常适合条形图,但对于时间条形图,它没有按预期工作,这是我的问题:

当我从api获取数据时,例如24小时内有50条记录,并将其显示在图表中,我只想显示10个条形(用户可以向左或向右平移以查看下一个数据(,但图表总是显示所有条形

24小时条形图

我想让它像这样显示,这是我按日期获取的数据,10个日期显示总是有10个或更少的条

10天时间条形图

那么,如何归档条形图显示的限制数量呢?就像我得到了10多条记录,如何让它只显示10条,然后用户可以向左平移以查看下一个数据

我在图表中使用了一些选项

{
animation: {
duration: 0,
},
maintainAspectRatio: false,
responsive: true,
scales: {
y: {
beginAtZero: true,
grid: {
drawBorder: false,
},
grace: '10%',
},
x: {
grid: {
display: false,
},
type: 'time',
display: true,
time: {
unit: 'day',
unitStepSize: 1,
displayFormats: {
day: ChartOptionConstants.DATE_FORMAT,
},
},
title: {
display: true,
text: 'DOC',
},
ticks: {
autoSkip: true,
maxRotation: 0,
maxTicksLimit: 8
},
},
},
interaction: {
mode: 'index',
intersect: false,
},
plugins: {
title: {
display: false,
text: this.chartTitle,
},
legend: {
display: true,
labels: {
font: {
size: 9,
},
usePointStyle: true,
},
},
tooltip: {
position: 'top',
caretSize: 0,
},
},
};

缩放插件选项

{
pan: {
enabled: true,
mode: 'x',
},
zoom: {
wheel: {
enabled: true,
},
pinch: {
enabled: true,
},
mode: 'x',
},
};

缩放插件在其配置中提供limits节点,您可以在其中设置轴上的limtis。

也许它可以帮助您的用例:https://www.chartjs.org/chartjs-plugin-zoom/latest/guide/options.html#limits

这对我很有用。你可以在下面的图表配置中硬编码为缩放限制。

const config = {
type: 'line',
data: data,
options: {
animation: false,
spanGaps: true,
showLine: true,
animation: {
duration: 0 // general animation time
},
hover: {
animationDuration: 0 // duration of animations when hovering an item
},
responsiveAnimationDuration: 0, // animation duration after a resize
autoSkipPadding: 100,
plugins: {
zoom: {
limits: {
x: {
minRange: getMinZoomRange(), // This is smallest time window you want to zoom into
min: 1680516080000,
max: 1680616080000,
},
},
pan: {
enabled: true,
mode: 'x'
},
zoom: {
wheel: {
enabled: true,
},
pinch: {
enabled: true
},
mode: 'x',
}
}
},
scales: {
x: {
type: 'time',
time: {
// tooltipFormat: "yyyy-MMM-dd HH:mm",
displayFormats: {
day: "d-MMM HH:mm",
millisecond: "HH:mm:ss.SSS",
second: "HH:mm:ss",
minute: "HH:mm",
hour: "d-MMM HH:mm",
},
// unit: granularity.toLowerCase(),
},
// min: 0,
// max: 0,
ticks: {
source: 'auto'
},
displayFormats: {
second: 'MMM YYYY'
}
},
y: {
beginAtZero: true,
title: {
display: true,
text: 'Time in Seconds'
}
},
requests: {
type: 'linear',
position: 'right',
min: 0,
max: 100
}
}
}
};

然后,您可以通过程序对其进行更改,如下所示。dataChart是Chart对象。

dataChart.config.options.plugins.zoom.limits.x.min = appDataSet['timeStamps'][0];
dataChart.config.options.plugins.zoom.limits.x.max = appDataSet.timeStamps[appDataSet['timeStamps'].length - 1];

最新更新