react-chartjs-2 fill property not working? - reactjs

I want to add fill to a line chart using the react-chartjs-2 package. I'm passing fill: true to the dataset but that doesn't work as expected. Any suggestions?
const data = {
labels,
datasets: [
{
label: "Balance",
data: history.balances.map((item) => item.balance),
fill: true,
borderColor: "rgba(190, 56, 242, 1)",
backgroundColor: "rgba(190, 56, 242, 1)",
tension: 0.3,
},
],
};

This is because you are using treeshaking and not importing/registering the filler plugin.
import {Chart, Filler} from 'chart.js';
Chart.register(Filler);

Related

Making fixed y-Axis scales with react-chartjs-2

i want to create a chart with Chart.js and React that has a persistant yAxis ranging form -15 to 15 with a stepSize of 5.
As an example i copied the dynamic Bar Chart that can be found here:
https://reactchartjs.github.io/react-chartjs-2/#/dynamic-bar
the documentation of charjs.org mentions min and max properties of the Axis here:
https://www.chartjs.org/docs/3.2.0/samples/scales/linear-min-max.html
but react-chartjs-2 seems to ignore these values. I tried:
Old Naming: scales.yAxis
New Naming: scales.y
adding "scaleOverride : true" to options.scales and option.scales.y
inside the "ticks"
outside the "ticks"
Removing everything in the config.scales.y but min, max and stepsize with old and new naming
My current App.js:
import React, { useEffect, useState } from 'react';
import { Bar } from 'react-chartjs-2';
const rand = () => Math.round(Math.random() * 20 - 10);
const genData = () => ({
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [
{
label: 'Scale',
data: [rand(), rand(), rand(), rand(), rand(), rand()],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)',
],
borderWidth: 1,
},
],
});
const options = {
scales: {
scaleOverride : true,
y: [
{
type: "time",
ticks: {
min: 0,
max: 150,
stepSize: 20
},
},
],
x: [
{
type: "Amp",
ticks: {
},
},
],
},
};
function App() {
const [data, setData] = useState(genData());
useEffect(() => {
const interval = setInterval(() => setData(genData()), 1000);
return () => clearInterval(interval);
}, []);
return (
<>
<Bar className="Linechart" data={data} options={options} />
</>
);
};
export default App;
Can someone please explain to me what is the correct way to set the y-Axis to a fixed range? Thanks in advance.
It was a simple syntax error. Using this config works:
const options = {
scales: {
y:
{
min: -15,
max: 15,
stepSize: 5,
},
x:
{
},
},
};
According to the documentation, use this
scales: {
y: {
min: -1,
max: 1,
ticks: {
stepSize: 1,
},
},
},
Basically, add the stepSize inside the ticks prop
The above accepted answer did not seem to work for me.
I found this solution and it works just fine customising the scale on the y-axis of the bar chart using react-chartjs-2 library.
const chartOptions = {
scales: {
yAxes: [{
ticks: {
beginAtZero: false,
min: 0,
stepSize: 2,
callback: function(value) {
return `${value}`
}
}
}]
}
}
use this Object in your barchart like so:
<Bar data={data} options={chartOptions} />

Dynamically add x-axis in React using ChartJS

I want to add another x axis to my ChartJS which works, but the scales do not separate, for example I want one label on the x-axis with 0-9 and another one 0-16 to show separately. It works perfectly fine for the y-axis but not for the x-axis.
Now for the code:
here I create an initial state
let state = {
labels: [],
datasets: [
{
label: 'ignore',
fill: false,
lineTension: 0,
backgroundColor: 'rgba(109, 24, 172, 1)',
borderColor: 'rgba(109, 24, 172, 1)',
borderWidth: 0.1,
pointRadius: 0.2,
data: []
}, {
label: 'ignore1',
fill: false,
lineTension: 0,
backgroundColor: 'rgba(0, 250, 255, 1)',
borderColor: 'rgba(0, 250, 255, 1)',
borderWidth: 0.1,
pointRadius: 0.2,
data: []
}
]
};
Here is my first function with 9 datapoints:
function adddataset(){
let lineChart = Chart.instances[0];
const data=lineChart.data;
const newDataset = {
label: 'Dataset ' + (data.datasets.length + 1),
backgroundColor: 'rgba(109, 24, 172, 1)',
borderColor: 'rgba(0, 250, 255, 1)',
data: [65, 59, 80, 81, 56, 55, 40],
yAxisID: 'By',
xAxisID: 'Bx',
};
lineChart.data.datasets.push(newDataset);
lineChart.update();
}
here is my second function to add a second dataset:
function adddataset1(){
let lineChart = Chart.instances[0];
const data=lineChart.data;
const newDataset = {
label: 'Dataset ' + (data.datasets.length + 1),
backgroundColor: 'rgba(rgba(109, 24, 172, 1)',
borderColor: 'rgba(109, 24, 172, 1)',
data: [100,30,50,60,20,30,60,100,34,3456,6,5,4,3,5,545],
yAxisID: 'Cy',
xAxisID: 'Cx',
};
lineChart.data.datasets.push(newDataset);
lineChart.update();
}
now here is my class where I initialize the LineGraph and have 2 buttons which call the functions
class About extends React.Component {
render() {
return (
<body>
<main>
Graph
<div className='Graph'>
<div style={{ height: 500 }}>
<Line
id="mychart"
data={state}
options={{
title: {
display: true,
text: 'Average Rainfall per month',
fontSize: 20
},
legend: {
display: true,
position: 'right'
},
maintainAspectRatio: false,
responsive: true
}}
/>
</div>
</div>
<button onClick={adddataset1}>
Button1
</button>
<button onClick={adddataset}>
Button2
</button>
</main>
</body>
);
}
}
export default About;
There are 2 solutions for your problem, you can either provide your data in object format so the labels get taken from the object like so:
const data = [{x: '1', y: 5}, {x: '2', y: 3}];
Or you can add a second x axis with the correct ID to all the scales which has a labels array property in which you can specify the labels for that scale so you will get something like this:
const myChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
myChart.options.scales['secondX'] = {
labels: ['6', '7', '8'],
position: 'bottom'
}
myChart.update();

How to use chartjs-plugin-trendline with react-chartjs-2

I want to add 'Trend' line to my line chart. I am using react-chartjs-2 to draw charts on my website. The code looks like:
import { Line } from 'react-chartjs-2';
import trendlineLinear from 'chartjs-plugin-trendline';
const PatientInfectionChart = ({ data, labels }) => {
const datasets = [
{
data: data.totalInfected,
backgroundColor: 'rgb(233, 85, 0)',
borderColor: 'rgba(233, 85, 0, 0.7)',
label: 'Today Infected',
},
{
data: data.todayRecovered,
backgroundColor: 'rgb(23, 198, 113)',
borderColor: 'rgba(23, 198, 113, 0.7)',
label: 'Today Recovered',
trendlineLinear: {
style: 'rgb(23, 198, 113)',
lineStyle: 'dotted',
width: 2,
},
},
];
return (
<Line
data={{ datasets, labels }}
plugins={[trendlineLinear]}
options={{
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
},
},
}}
/>
);
};
export default PatientInfectionChart;
However, I get the following error:
Uncaught TypeError: Cannot read property 'ctx' of undefined
at Object.afterDraw (chartjs-plugin-trendline.js:23)
at callback (helpers.segment.js:89)
at PluginService._notify (chart.esm.js:4737)
at PluginService.notify (chart.esm.js:4724)
at Chart.notifyPlugins (chart.esm.js:5788)
at Chart.draw (chart.esm.js:5537)
at chart.esm.js:66
at Map.forEach (<anonymous>)
at Animator._update (chart.esm.js:44)
at chart.esm.js:34
How to I fix this?
The trendline plugin requires chart.js version 2, react chart.js uses version 3 so you will need to downgrade react-chartjs
Commands:
yarn remove react-chartjs-2
yarn add react-chartjs-2#2.11.2

add numeric value with different color in radar labels

I am new to chart.js. i need help in adding a numeric value to radar chart point labels with different color. eg radar label with styling
labels color should be in black.
numeric value should be in a different predefined color(eg blue).
new Chart('radar-chart', {
type: 'radar',
data: {
labels: ['mon 30', 'tue 40', 'thurs 25', 'fri 45', 'sat 67', 'sun 50'],
datasets: [{
label: 'My First Dataset',
data: [65, 59, 90, 81, 56, 55],
fill: true,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgb(255, 99, 132)',
pointBackgroundColor: 'rgb(255, 99, 132)',
pointBorderColor: '#fff',
pointHoverBackgroundColor: '#fff',
pointHoverBorderColor: 'rgb(255, 99, 132)'
}],
},
options: {
plugins: {
legend: {
display: false
}
},
scales: {
r: {
pointLabels: {
color: 'black',
font: {
size: 20,
style: 'italic'
}
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.2.0/chart.min.js"></script>
<canvas id="radar-chart"></canvas>
the values near the labels in vertex should be in a predefined color(eg blue) -like the one attached in image.
please feel free to give a different approach to achieve this requirement. Thanks in advance for the help.

How can I remove the grid line in the background of the line chart?

I am working on a React JS project. In my project, I need to create line chart components. I am trying to use Chart JS 2 library for React JS. But, now I am having a little problem customising the line chart. I want to remove the grids and the lines in the background (screenshot) and the label at the top of the chart (My first dataset).
This is my code.
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: 'My First dataset',
fill: true,
lineTension: 0.1,
backgroundColor: '#edfce9',
borderColor: '#3DAA1D',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: '#3DAA1D',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: '#3DAA1D',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40],
showLine: true
}
]
};
<Line data={data} />
How can I do that? Removing the grids (lines) in the background of the chart and removing the label at the top (My First dataset)?
Please take a look at the documentation. You can disable gridlines in the options (which you will have to add)
https://www.chartjs.org/docs/2.9.4/axes/cartesian/#common-configuration
options: {
scales: {
yAxes: [
gridLines: {
display: false
}
],
xAxes: [
gridLines: {
display: false
}
]
},
legend: {
display: false
}
}
V3:
options: {
scales: {
x: {
grid: {
display: false
}
},
y: {
grid: {
display: false
}
}
}
}

Resources