x -如何在水平条形图的两侧复制x轴只有1个数据集?



我正在尝试复制图表两侧(底部和顶部)的X轴刻度。

我见过这个问题的老问题,但这是在chartjs 2。x——从那时起,他们改变了期权的比例部分。你过去可以做类似这样的事情:

xAxes: [
{
position: 'top',
},
{
position: 'bottom',
}
]

但是在图表3中。你不能为xAxes提供数组。你现在需要添加一个ID到你的数据集,然后在scale options中引用这个ID。但是当一个说位置:顶部和另一个位置:底部时,我不能在2个尺度对象中引用1个数据集。它将只使用最后一个缩放对象。

所以我的问题是,一个数据集。我怎么能让X轴在图表的底部和水平条形图的顶部?这样,如果图表很大,我就不必总是向下滚动来查看值。

编辑:根据反馈,我现在有以下结果,这更接近我正在寻找的,但顶部的刻度发生了什么。为什么它们与底部的数字不匹配?

new Chart('myChart', {
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D', 'E', 'F'],
datasets: [{    
data: [1, 3, 6, 2, 8, 9],
borderColor: '#00D',
}]
},
options: {
indexAxis: "y",
scales: {
x: {
},
x1: {
position: 'top'
}
}
}
});
canvas {
max-height: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart"></canvas>

如果您希望在图表顶部看到相同的ticks,只需定义第二个x轴,如下所示:

x1: {
position: 'top'
}

请看看下面的可运行代码,看看它是如何工作的:

new Chart('myChart', {
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D', 'E', 'F'],
datasets: [{    
data: [1, 3, 6, 2, 8, 9],
borderColor: '#00D',
}]
},
options: {
scales: {
x: {
},
x1: {
position: 'top'
}
}
}
});
canvas {
max-height: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart"></canvas>

如果您想生成一个水平条形图,您可以这样定义x轴:

scales: {
x: {
min: 0
},
x1: {
position: 'top',
min: 0,
max: 9
}
}

请看看下面的可运行示例,看看当数据是动态的时它是如何工作的:

var data = [3, 6, 8, 9, 31];
new Chart('myChart', {
type: 'bar',
data: {
labels: ['A', 'B', 'C', 'D', 'E'],
datasets: [{
data: data,
borderColor: '#00D',
}]
},
options: {
indexAxis: 'y',
plugins: {
legend: {
display: false
}
},
scales: {
x: {
min: 0
},
x1: {
position: 'top',
min: 0,
suggestedMax: Math.max(...data)
}
}
}
});
canvas {
max-height: 180px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<canvas id="myChart"></canvas>

最新更新