我很难通过charts.js和双轴水平条形图获得正确的xAxis设置。 JsFiddle链接如下。麻烦的是我试图在同一个图表中显示两个不同的比例。一个是高数字(价格),另一个是低数字(数量)。
https://jsfiddle.net/clevelandbuckeye/Luaf2tm4/533/
我在options属性中使用了第二个x-axis,但标签显示为Month,而不是数量!如何显示数量?
<canvas id="myChart" width="400" height="200"></canvas>
<script>
var canvas = document.getElementById('myChart');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "# Deals",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [15, 19, 5, 16, 1, 12, 8],
xAxisID:'x1',
}, {
label: "$Money",
backgroundColor: "rgba(55,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(55,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [265, 459, 320, 181, 456, 555, 1040]
}]
};
var option = {
scales: {
yAxes: [{
gridLines: {
display: true,
color: "rgba(255,99,132,0.2)"
}
}],
xAxes: [{
id: 'x1',
gridLines: {
display: false
}},
{
id: 'x2',
gridLines: {
display: false
}
}]
}
};
var ctx = document.getElementById("myChart").getContext('2d');
var myBarChart = new Chart(ctx, {
type: 'horizontalBar',
data: data,
options: option
});
</script>
答案 0 :(得分:4)
<强>ꜰɪʀꜱᴛ强>
为第二个数据集设置 xAxisID: 'x2'
,如下:
datasets: [{
...
}, {
label: "$Money",
backgroundColor: "rgba(55,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(55,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [265, 459, 320, 181, 456, 555, 1040],
xAxisID: 'x2',
}]
<强>ꜱᴇᴄᴏɴᴅ强>
为第二个x轴设置 type: 'linear'
和 position: 'bottom'
,如下所示:
xAxes: [{
...
}, {
id: 'x2',
type: 'linear',
position: 'bottom',
gridLines: {
display: false
}
}]
ᴡᴏʀᴋɪɴɢᴡᴏʀᴋɪɴɢxᴀᴍᴘʟᴇᴀᴍᴘʟᴇ
var canvas = document.getElementById('myChart');
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "# Deals",
backgroundColor: "rgba(255,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 2,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [15, 19, 5, 16, 1, 12, 8],
xAxisID: 'x1',
}, {
label: "$Money",
backgroundColor: "rgba(55,99,132,0.2)",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(55,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [265, 459, 320, 181, 456, 555, 1040],
xAxisID: 'x2',
}]
};
var option = {
scales: {
yAxes: [{
gridLines: {
display: true,
color: "rgba(255,99,132,0.2)"
}
}],
xAxes: [{
id: 'x1',
gridLines: {
display: false
}
}, {
id: 'x2',
type: 'linear',
position: 'bottom',
gridLines: {
display: false
}
}]
}
};
var ctx = document.getElementById("myChart").getContext('2d');
var myBarChart = new Chart(ctx, {
type: 'horizontalBar',
data: data,
options: option
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.3/Chart.min.js"></script>
<canvas id="myChart" width="400" height="200"></canvas>