我正在尝试使用 Chart.js 创建此图表。
挑战:
到目前为止我的代码:
new Chart(ctx, {
type: 'line',
data: {
labels: ['Buy', 'Sell'],
datasets:
[
...grid.pairs.map(pair => {
return {
data: [pair.buyPrice, pair.sellPrice],
borderColor: '#0d6efd',
backgroundColor: '#0d6efd',
pointRadius: [3, 5],
}
}),
{
label: 'Market Price',
data: [grid.marketPrice, grid.marketPrice],
borderColor: 'red',
backgroundColor: 'red',
}
]
},
options: {
scales: {
x: {
},
y: {
title: {
display: true,
text: 'Price in Euro'
},
}
},
}
})
我可以得到一些帮助吗?
通过将其制作为
bar
图表,数据点按照要求位于每个条形的中心。各个数据系列应为 type: 'line'
const ctx = document.getElementById('myChart');
const grid = {
marketPrice: 12,
pairs: [{
buyPrice: 12,
sellPrice: 3
},
{
buyPrice: 16,
sellPrice: 6
},
{
buyPrice: 17,
sellPrice: 2
},
]
}
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Buy', 'Sell'],
datasets: [
...grid.pairs.map((pair, index) => {
return {
label: 'Series ' + index,
type: 'line',
data: [pair.buyPrice, pair.sellPrice],
borderColor: '#0d6efd',
backgroundColor: '#0d6efd',
pointRadius: [3, 5],
}
}),
{
type: 'line',
label: 'Market Price',
data: [grid.marketPrice, grid.marketPrice],
borderColor: 'red',
backgroundColor: 'red',
}
]
},
options: {
scales: {
x: {},
y: {
title: {
display: true,
text: 'Price in Euro'
},
}
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js" integrity="sha512-ZwR1/gSZM3ai6vCdI+LVF1zSq/5HznD3ZSTk7kajkaj4D292NLuduDCO1c/NT8Id+jE58KYLKT7hXnbtryGmMg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div>
<canvas id="myChart"></canvas>
</div>