图表J的折线图时间笛卡尔轴的刻度数和线偏移量



我正在尝试制作一张图表来显示过去7天的数据。我的x轴-是一个时间笛卡尔轴,时间单位设置为"天",但图表只显示6个刻度,我想显示7个刻度,每天一个刻度。

此外,刻度线偏移到图表点,我希望这些点与刻度线完全对齐

let [priceData, scoreData] = generateFakeData(7);
// max price to show on the chart is max price + 1000
const maxPrice = Math.max(...priceData.map(data => data.y)) + 1000;
//console.log(data);
console.log(priceData[0].x);
console.log(priceData[scoreData.length - 1].x);
function generateRandomNumber(min, max) {
return Math.floor(Math.random() * max) + min;
}
const ctx = document.getElementById('chart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
pointRadius: 0,
options: {
elements: {
point: {
pointRadius: 0,
pointHoverRadius: 3
}
},
interaction: {
mode: 'nearest',
intersect: false,
axis: 'x'
},
plugins: {
legend: {
labels: {
// This more specific font property overrides the global property
color: '#fff',
font: {
size: 14,
}
}
}
},
scales: {
x: {
type: 'time',
beginAtZero: true,
ticks: {
color: "white",
autoSkip: false,
maxTicksLimit: 7,
count: 7,
},
time: {
displayFormats: {
month: 'dd MMM yy'
},
unit: 'day'
},
gridLines: {
offsetGridLines: true,
},
offset: false,
},
y: {
type: 'linear',
min: 0,
max: maxPrice,
ticks: {
color: "white"
}
},
y1: {
type: 'linear',
min: 0.5,
max: 10.5,
display: true,
position: 'right',
ticks: {
color: "white",
autoSkip: false,
maxTicksLimit: 12,
callback: function (val, index) {
// Hide first and last tick label
return val === 0.5 || val === 10.5 ? '' : this.getLabelForValue(val);
},
},
// grid line settings
grid: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
},
}
},
data: {
datasets: [
{
label: 'price',
data: priceData,
borderColor: [
'#ffb800'
],
borderWidth: 1
},
{
label: 'score',
data: scoreData,
borderColor: [
'#00ff00'
],
borderWidth: 1,
yAxisID: 'y1',
}
]
}
});
function generateFakeData(numOfDays) {
const priceData = [];
const scoreData = [];
let today = new Date();
priceData.unshift({ x: new Date(today), y: generateRandomNumber(1000, 2500) });
scoreData.unshift({ x: new Date(today), y: generateRandomNumber(1, 10) });
for (let i = 0; i < numOfDays - 1; i++) {
const newDate = today.setDate(today.getDate() - 1);
priceData.unshift({ x: new Date(newDate), y: generateRandomNumber(1000, 2500) });
scoreData.unshift({ x: new Date(newDate), y: generateRandomNumber(1, 10) });
}
return [priceData, scoreData];
}
html {
background-color: black
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
</head>
<body>
<canvas id="chart"></canvas>
</body>
</html>

链接到jsBin:https://jsbin.com/viduman/5/edit?html,js,输出

我只需要将每天的小时设置为(0,0,0,0(

let today = new Date();
today.setHours(0, 0, 0, 0);

最新更新