如何根据数据集组织数据?
// Bar Chart Example
var ctx = document.getElementById("myBarChart");
var myLineChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [ "Mar", "Apr", ],
datasets: [
{
label: "serj",
backgroundColor: "#11564D",
borderColor: "rgba(2,117,216,1)",
data: [{x: "Mar", y: 128400}, {x: "Apr", y: 53500}, ],
},
{
label: "aisha",
backgroundColor: "#508D2F",
borderColor: "rgba(2,117,216,1)",
data: [{x: "Mar", y: 58500}, {x: "Apr", y: 12000}, ],
},
{
label: "serikzhan",
backgroundColor: "#3F22F5",
borderColor: "rgba(2,117,216,1)",
data: [{x: "Apr", y: 8000}, ],
},
],
},
options: {
scales: {
xAxes: [{
time: {
unit: 'month',
},
gridLines: {
display: false
},
ticks: {
maxTicksLimit: 6
}
}],
yAxes: [{
ticks: {
min: 0,
max: 150000,
maxTicksLimit: 5
},
gridLines: {
display: true
}
}],
},
legend: {
display: false
}
}
});
自动创建的所有数据集和标签。问题是所有数据从三月开始,不依赖于 x 轴。不同的用户在不同的月份有不同的数据。我们是否可以只使用 ChartJS api 来解决这个问题?
最佳答案
你的方法几乎没问题。唯一需要更改的是删除 data.labels
并定义 xAxis
,如下所示:
xAxes: [{
offset: true,
type: 'time',
time: {
parser: 'MMM',
unit: 'month',
displayFormats: {
month: 'MMM'
}
},
Please note that Chart.js uses Moment.js for the functionality of the time axis. Therefore you should use the bundled version of Chart.js that includes Moment.js in a single file.
var ctx = document.getElementById("myBarChart");
var myLineChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [
{
label: "serj",
backgroundColor: "#11564D",
borderColor: "rgba(2,117,216,1)",
data: [{x: "Mar", y: 128400}, {x: "Apr", y: 53500}]
},
{
label: "aisha",
backgroundColor: "#508D2F",
borderColor: "rgba(2,117,216,1)",
data: [{x: "Mar", y: 58500}, {x: "Apr", y: 12000}]
},
{
label: "serikzhan",
backgroundColor: "#3F22F5",
borderColor: "rgba(2,117,216,1)",
data: [{x: "Apr", y: 8000}]
}
]
},
options: {
scales: {
xAxes: [{
offset: true,
type: 'time',
time: {
parser: 'MMM',
unit: 'month',
displayFormats: {
month: 'MMM'
}
},
gridLines: {
display: false
},
ticks: {
maxTicksLimit: 6
}
}],
yAxes: [{
ticks: {
min: 0,
max: 150000,
maxTicksLimit: 5
},
gridLines: {
display: true
}
}],
},
legend: {
display: false
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="myBarChart" height="90"></canvas>
关于javascript - Chartjs不同长度的标签和数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61026564/