Reputation: 1087
I try to draw multi line chart (single line doesn't work as well) using react-chartjs-2 Line
component
My data structure
const data = {
labels: dataFromDb.map(item => item.period),
datasets: [
{
data: dataFromDb,
backgroundColor: '#FAA46A',
borderColor: '#FAA46A',
label: i18n.sellPrice,
parsing: { yAxisKey: 'price_so' },
},
{
data: dataFromDb,
backgroundColor: '#1DCF35',
borderColor: '#1DCF35',
label: i18n.purchasePrice,
parsing: { yAxisKey: 'price_po' },
},
],
};
Data from db is array of objects {period: string, price_so: number, price_po: number, quantity: number}
My chart
<Line
height={400}
data={data}
options={{
animation: false,
maintainAspectRatio: false,
elements: { line: { tension: 0.4 } },
scales: {
x: { grid: { display: false }, offset: true },
y: {
title: { text: i18n.amount, display: true },
grid: { display: false },
},
},
}}
/>
Problem is that none of the lines Visible. I can see that data is read as y axis have values mapped by object properties price_so
and price_po
(900 is highest value for price_po in objects array from db) and legend recognized datasets as correct colors applied but lines not draw. Am I missing something in configuration?
Upvotes: 2
Views: 1014
Reputation: 8890
You should also set xAxisKey
in parsing
. It seems logical that the library would use period
since you defined the labels as such, but apparently it doesn't make that infferrence by itself.
Here's a non-react example based on your code, with invented data:
const dataFromDb = [
{period: '2019', price_so: 100, price_po: 110},
{period: '2020', price_so: 120, price_po: 120},
{period: '2021', price_so: 110, price_po: 109},
{period: '2022', price_so: 90, price_po: 100},
{period: '2023', price_so: 105, price_po: 115},
];
const data = {
labels: dataFromDb.map(item => item.period),
datasets: [
{
data: dataFromDb,
backgroundColor: '#FAA46A',
borderColor: '#FAA46A',
label: 'sellPrice',
parsing: { xAxisKey: 'period', yAxisKey: 'price_so' },
},
{
data: dataFromDb,
backgroundColor: '#1DCF35',
borderColor: '#1DCF35',
label: 'purchasePrice',
parsing: { xAxisKey: 'period', yAxisKey: 'price_po' },
},
],
};
const options={
animation: false,
maintainAspectRatio: false,
/*elements: { line: { tension: 0.4 } },*/
scales: {
x: { grid: { display: false }, offset: true },
y: {
title: { text: 'amount', display: true },
grid: { display: false },
},
},
};
new Chart(document.querySelector('#line-chart'), {type:'line', data, options});
<div id="line-chart-container">
<canvas id="line-chart"></canvas>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.2/chart.umd.js"
integrity="sha512-t41WshQCxr9T3SWH3DBZoDnAT9gfVLtQS+NKO60fdAwScoB37rXtdxT/oKe986G0BFnP4mtGzXxuYpHrMoMJLA=="
crossorigin="anonymous" referrerpolicy="no-referrer">
</script>
Upvotes: 1