gpt4 book ai didi

javascript - Chart.js 时间序列跳过几天

转载 作者:行者123 更新时间:2023-12-02 20:06:21 35 4
gpt4 key购买 nike

我有一个非常简单的条形图,其中每个数据点由日期(天)和数字组成。也许唯一的特点是并非每个日期都被涵盖(即有些日子没有数据点)。

绘制图表时,仅显示那些具有与其关联的数据点的日期。所有其他日期都被简单地省略。因此 x 轴分布不均匀并且会跳过值。

Faulty graph

如何确保 X 轴真正呈线性且不会遗漏任何日期?

PS:这就是我的图表的定义方式:

chartData.datasets[0].data.push( {t: new Date('2019-02-01'), y: value});
// And so on...

var chart = new Chart(ctx, {
type: 'bar',
data: chartData,
options: {
annotation: {
annotations: []
},
legend: {
display: false
},
scales: {
xAxes: [{
type: 'time',
unitStepSize: 1,
distribution: 'series',
time: {
unit: 'day'
},
}]
}
}
});

最佳答案

这是此问题的有效解决方案,适用于新版本的 Chart.js v3.x

Chart.js v3.2.1(不向后兼容v2.xx)

const ctx = document.getElementById('timeSeriesChart').getContext('2d');

const chartData = [
{x:'2019-01-08', y: 4},
{x:'2019-01-13', y: 28},
{x:'2019-01-14', y: 8},
{x:'2019-01-15', y: 18},
{x:'2019-01-16', y: 68},
{x:'2019-01-18', y: 48},
{x:'2019-01-19', y: 105},
{x:'2019-01-21', y: 72},
{x:'2019-01-23', y: 36},
{x:'2019-01-24', y: 48},
{x:'2019-01-25', y: 17},
{x:'2019-01-28', y: 30},
{x:'2019-01-29', y: 28},
{x:'2019-01-30', y: 25},
{x:'2019-01-31', y: 18},
{x:'2019-02-04', y: 25},
{x:'2019-02-05', y: 22},
{x:'2019-02-06', y: 17},
{x:'2019-02-07', y: 15}
];

const chart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
data: chartData,
backgroundColor: 'rgb(189,0,53)'
}]
},
options: {
plugins: {
legend: { //watch out: new syntax in v3.2.0, `legend` within `plugins`
display: false
},
title: { //watch out: new syntax in v3.2.0, `title` within `plugins`
display: false
}
},
scales: {
x: { //watch out: new syntax in v3.2.0 for xAxis
type: 'timeseries', // `time` vs `timeseries` later in images
time: {
unit: 'day'
},
ticks: { // Edit: added this to avoid overlapping - thanks for comment
minRotation: 85, // <-- just try any number
maxRotation: 90 // <-- just try any number
}
}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<!-- gets you latest version of Chart.js (now at v3.2.1) -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script>
<!-- for x-Axis type 'time' or 'timeseries' to work, you need additional libraries -->
<!-- (like moment.js and its adapter) -->

<div>
<canvas id="timeSeriesChart"></canvas>
</div>

时间笛卡尔轴

x: {
type: 'time'

按照您的要求使 x 轴“线性”,仍然显示没有数据的天数

来源:https://www.chartjs.org/docs/latest/axes/cartesian/time.html

Time Cartesian Axis

时间序列

x: {
type: 'timeseries'

使数据点等距并相应地调整 x 轴以使条形显示均匀分布

来源:https://www.chartjs.org/docs/latest/axes/cartesian/timeseries.html

Time Series Axis

编辑:在回复评论时避免x轴刻度线重叠: timeseries without overlapping x-Axis ticks

到目前为止,我们已经展示了 timetimeseries 类型之间的区别

关于javascript - Chart.js 时间序列跳过几天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54590416/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com