我正在尝试在chart.js中构建一个图表,以显示虚拟商品的价格数据,以折线图显示价格,并以备用条形图显示销售量,如下所示:
我的问题是,两者的y轴都相同,这意味着价格数据显示在底部,没有明显的差异,因为数量有数百个。
我希望价格数据显示在y轴上,条形图相对显示,最大体积显示为100%高度,而不是y轴上的值,更像这样:
这可能吗,怎么办?谢谢!
代码:
let marketData = [["Nov 28 2018 20: +0",30.332,"103"],["Nov 28 2018 21: +0",25.801,"188"],["Nov 28 2018 22: +0",25.451,"262"],["Nov 28 2018 23: +0",12.484,"693"]];
let lineData = [];
let barData = [];
let labels = [];
marketData.forEach(function(thing) {
labels.push(thing[0].replace(' +0', '00'));
lineData.push(thing[1]);
barData.push(thing[2]);
});
new Chart(document.getElementById("mixed-chart"), {
type: 'bar',
data: {
labels: labels,
datasets: [
{
label: "Price",
type: "line",
borderColor: "#3e95cd",
data: lineData,
fill: false
},
{
label: "Sold",
type: "bar",
backgroundColor: "rgba(0,0,0,0.2)",
data: barData
}
]
},
options: {
title: {
display: true,
text: 'Sale price vs sale volume'
},
legend: { display: false }
}
});
答案 0 :(得分:1)
使用第二个y轴为条形图系列赋予不同的比例
使用属性-> yAxisID
然后在id
选项中设置y轴的匹配scales.yAxes
请参阅以下工作片段...
$(document).ready(function() {
let marketData = [["Nov 28 2018 20: +0",30.332,"103"],["Nov 28 2018 21: +0",25.801,"188"],["Nov 28 2018 22: +0",25.451,"262"],["Nov 28 2018 23: +0",12.484,"693"]];
let lineData = [];
let barData = [];
let labels = [];
marketData.forEach(function(thing) {
labels.push(thing[0].replace(' +0', '00'));
lineData.push(thing[1]);
barData.push(thing[2]);
});
new Chart(document.getElementById("mixed-chart"), {
type: 'bar',
data: {
labels: labels,
datasets: [
{
label: "Price",
type: "line",
borderColor: "#3e95cd",
data: lineData,
fill: false,
yAxisID: 'A' // <-- set y-axis id
},
{
label: "Sold",
type: "bar",
backgroundColor: "rgba(0,0,0,0.2)",
data: barData,
yAxisID: 'B' // <-- set y-axis id
}
]
},
options: {
title: {
display: true,
text: 'Sale price vs sale volume'
},
legend: {display: false},
scales: {
yAxes: [{
id: 'A', // <-- set y-axis id
position: 'left',
}, {
id: 'B', // <-- set y-axis id
position: 'right',
// hide grid lines and labels
gridLines: {
display: false
},
ticks: {
display: false
}
}]
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.min.js"></script>
<canvas id="mixed-chart"></canvas>