gpt4 book ai didi

javascript - ChartJS 如何设置 X 轴的最大标签?

转载 作者:行者123 更新时间:2023-11-29 15:11:35 25 4
gpt4 key购买 nike

我从一个数组接收图表数据,我在数组中存储了从 2016 年 1 到 2018 年 12 的日期。在图表中,它显示了 3 年的所有月份。但我只需要展示 1 年。有什么想法吗?

这里我传递了一个数组并更改了月份的单位,还有 displayFormats

chartHour.config.data.datasets[0].data = array
chartHour.config.options.scales.xAxes[0].time = {
unit: "month",
stepSize: 1,
displayFormats: {
month: "MMM",
},
}

最佳答案

您可以通过在 time 键下定义 minmax 值来实现。

If min or max is defined, this will override the data minimum or maximum respectively. See docs for more info.

chartHour.config.options.scales.xAxes[0] = {
type: "time",
time: {
min: "2017-01-01",
max: "2017-12-01",
displayFormats: {
day: "MMM YY"
}
}
};

请参阅下面的工作示例。

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const years = [2016, 2017, 2018];

const labels = [];
const dataSet = [];
years.forEach((year, index) => {
months.forEach((month, monthIndex) => {
const date = moment(`${month} ${year}`, "MMM YYYY").format('YYYY-MM-DD');
labels.push(date);
dataSet.push({
x: date,
y: (monthIndex + 12) * (index + 1)
});
});
});

var data = {
labels: labels,
datasets: [{
pointRadius: 0,
label: "Positive",
lineTension: 0,
data: dataSet,
borderWidth: 1,
backgroundColor: "rgba(0, 255, 0, 0.5)"
}]
};
var options = {
scales: {
xAxes: [{
type: "time",
distribution: 'series',
time: {
min: "2017-01-01",
max: "2017-12-01",
displayFormats: {
day: 'MMM YY'
}
},
ticks: {
source: "labels"
},
gridLines: {
display: false
}
}]
}
};

var ctx = document.getElementById("myChart").getContext("2d");

var myBarChart = new Chart(ctx, {
type: "bar",
data: data,
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<canvas id="myChart" width="300" height="100"></canvas>

关于javascript - ChartJS 如何设置 X 轴的最大标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53961144/

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