Mixing chart with bar charts
Pedram-Parsian opened this issue · 3 comments
I want to build a mixed chart with bar chart, essentially adding "volumes" (in stock market) as bars sitting in bottom of chart, to make something like this:
Based on the docs, I tried the below code, but it didn't work as expected.
var barCount = 5;
var initialDateStr = '01 Apr 2020 00:00 Z';
var getRandomInt = function (max) {
return Math.floor(Math.random() * Math.floor(max));
};
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
function randomBar(date, lastClose) {
var open = randomNumber(lastClose * 0.95, lastClose * 1.05).toFixed(2);
var close = randomNumber(open * 0.95, open * 1.05).toFixed(2);
var high = randomNumber(Math.max(open, close), Math.max(open, close) * 1.1).toFixed(2);
var low = randomNumber(Math.min(open, close) * 0.9, Math.min(open, close)).toFixed(2);
return {
t: date.valueOf(),
o: open,
h: high,
l: low,
c: close
};
}
function getRandomData(dateStr, count) {
var date = luxon.DateTime.fromRFC2822(dateStr);
var data = [randomBar(date, 30)];
while (data.length < count) {
date = date.plus({days: 1});
if (date.weekday <= 5) {
data.push(randomBar(date, data[data.length - 1].c));
}
}
return data;
}
let ctx = document.getElementById('chart').getContext('2d');
var chart = new Chart(ctx, {
type: 'candlestick',
data: {
datasets: [{
label: 'Prices',
data: getRandomData(initialDateStr, barCount),
}, {
label: 'Volumes',
// adding some sample data to represent "volumes":
data: [200, 150, 600, 400, 200],
// Changes this dataset to become a line
type: 'bar'
}],
labels: ['January', 'February', 'March', 'April', 'May']
},
});
Is there any workaround to this issue? and BTW, how can I handle the scaling issue? Since "bar" values should always start at the bottom of page, and not directly comparable to "candles" .
You need to create two different y-axes. See the Chart.js docs
Could you please provide a complete working example? I tried adding yAxisID: "candles"
and yAxisID: "bars"
to "candlestick" and "bar" respectively, and also the following options:
options: {
scales: {
yAxes: [{
id: 'candles',
position: 'left',
}, {
id: 'bars',
type: 'linear',
position: 'right',
}]
}
}
but still no luck (the "bars" are not yet visible).