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

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

Related

ReferenceError: ResizeObserver is not defined with nivo and NextJS

I want to use nivo with Next but when I load the page containing a pie chart made with nivo, I get this error: ReferenceError: ResizeObserver is not defined.
My Pie.js component:
import { ResponsivePie } from "#nivo/pie";
export const data = [
{
id: "c",
label: "c",
value: 80,
color: "hsl(8, 70%, 50%)",
},
{
id: "lisp",
label: "lisp",
value: 188,
color: "hsl(122, 70%, 50%)",
},
{
id: "go",
label: "go",
value: 161,
color: "hsl(111, 70%, 50%)",
},
];
export default function MyPie({ data }) {
return (
<ResponsivePie
data={data}
margin={{ top: 40, right: 80, bottom: 80, left: 80 }}
innerRadius={0.5}
padAngle={0.7}
cornerRadius={3}
activeOuterRadiusOffset={8}
borderWidth={1}
borderColor={{ from: "color", modifiers: [["darker", 0.2]] }}
arcLinkLabelsSkipAngle={10}
arcLinkLabelsTextColor="#333333"
arcLinkLabelsThickness={2}
arcLinkLabelsColor={{ from: "color" }}
arcLabelsSkipAngle={10}
arcLabelsTextColor={{ from: "color", modifiers: [["darker", 2]] }}
defs={[
{
id: "dots",
type: "patternDots",
background: "inherit",
color: "rgba(255, 255, 255, 0.3)",
size: 4,
padding: 1,
stagger: true,
},
{
id: "lines",
type: "patternLines",
background: "inherit",
color: "rgba(255, 255, 255, 0.3)",
rotation: -45,
lineWidth: 6,
spacing: 10,
},
]}
/>
)
};
My chart.js page:
import MyPie, { data } from "../components/Pie";
import homeStyles from "../styles/Home.module.css";
function Chart() {
return (
<div className={homeStyles.divchart}>
<MyPie data={data}/>
</div>
);
};
export default Chart;
This error only appears when using ResponsivePie and not Pie. I also tried to make it work with a React project but though I don't get this error, Nothing seems to be displayed.
Edit:
After some investigations, it looks like there is something wrong with #nivo/core 0.79.0 dependency. We should open an issue on the GitHub repo. I made some changes to check whether it is caused by my version of Next.js but the bug occurs only with #nivo/core 0.79.0.
It turns out this was the result of a bug introduced in version 0.79.0, which was fixed in https://github.com/plouc/nivo/pull/1886.
You should update #nivo/core to 0.79.1.
It looks like #nivo/pie is not compatible with Next.js server-side rendering as it utilizes Web APIs (ResizeObserver).
To avoid importing MyPie (and subsequently ResponsivePie) on the server, you can dynamically import it on the client-side only using next/dynamic with ssr: false.
import dynamic from "next/dynamic";
import { data } from "../components/Pie";
import homeStyles from "../styles/Home.module.css";
const MyPie = dynamic(() => import("../components/Pie"), {
ssr: false
})
function Chart() {
return (
<div className={homeStyles.divchart}>
<MyPie data={data}/>
</div>
);
};
export default Chart;
It's likely that code is being run on server side (SSR), and ResizeObserver doesn't exist there. You should try to make sure that your code only executes when on client side.
It's hard for me to tell you how as I don't know what your setup is. You can likely just add a check to only run that part of the code if ResizeObserver is defined.
I hope at least this points you in the right direction.

react-chartjs-2 fill property not working?

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);

react I want to hide the y-axis values and tooltip in the react chart

I am using react-chart-2.
When I hover the line graph, the tooltip is displayed, but I want to hide the tooltip when I hover the line graph.
I also want to hide the numbers 0,0.1,0.2 to 1 on the left (y-axis) of the line graph.
How can I implement this to hide the y-axis of the line graph?
Also, how do I hide the tooltip in the line graph? 
 
code
import React from "react";
import { Bar } from "react-chartjs-2";
const data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "Sales",
type: "line",
data: [51, 300, 40, 49, 60, 37, 40],
fill: false,
borderColor: "#555555",
backgroundColor: "#555555",
pointBorderColor: "#000000",
pointBackgroundColor: "#EC932F",
pointHoverBackgroundColor: "#EC932F",
pointHoverBorderColor: "#EC932F",
yAxisID: "y-axis-1"
},
{
type: "bar",
label: "Visitor",
data: [200, 185, 590, 621, 250, 400, 95],
fill: false,
backgroundColor: "#F7C520",
borderColor: "#F7C520",
hoverBackgroundColor: "#E6B71E",
hoverBorderColor: "#E6B71E",
yAxisID: "y-axis-1"
}
]
};
const options = {
responsive: true,
tooltips: {
mode: "label"
},
elements: {
line: {
fill: false
}
},
scales: {
xAxes: [
{
display: true,
gridLines: {
display: true
}
}
],
yAxes: [
{
type: "linear",
display: true,
position: "left",
id: "y-axis-1",
gridLines: {
display: true
}
},
{
type: "linear",
display: true,
position: "right",
id: "y-axis-2",
gridLines: {
display: false
}
}
]
}
};
class MixExample extends React.Component {
render() {
return (
<div>
<h2>Mixed data Example</h2>
<Bar data={data} options={options} />
</div>
);
}
}
export default MixExample;
react-chartjs-2 has 2 major versions relevant to this issue: v2, which has support for chart.js 2.9.4 and below, and v3, which significantly changes a lot of options and configurations, and which supports chart.js 3.0.0 and above.
The original fork of your codesandbox link uses chart.js: 2.9.4 and react-chartjs-2: 2.1.1, which differs from the sandbox link you provided, which uses chart.js: 3.5.1 and react-chartjs-2: 3.0.4. Notably, instead of structuring your options object like
scales: {
x-axes: [ /* array of axis options... */],
y-axes: [ /* array of axis options... */],
}
where each axis has an axisID property, you structure them with the axisID as the key and the rest of the original options object is the value, such as:
scales: {
"x-axis-1": {
display: true,
gridLines: {
display: false
}
},
"y-axis-1": {
type: "linear",
display: false,
position: "left"
}
}
Furthermore, the tooltip can be disabled by moving the tooltip into plugins, as the chart.js docs say that tooltip is a part of plugins:
global options for the chart tooltips is defined in Chart.defaults.plugins.tooltip
Therefore, to disable the tooltip entirely:
plugins: {
tooltip: {
enabled: false
}
}
Since you want to only disable the tooltip for a single dataset, the solutions found here may be of some use, but I haven't tried either for myself. It may also be possible to set the global default for Chart.JS tooltips to false, then enable it on a dataset-by-dataset basis, as displayed here, accessing it via react-chartjs-2's chart ref.
For that level of customization, I would highly suggest starting from the beginning with the most up-to-date version of react-chartjs-2 and the examples therein, rather than your current v2-configured starting point.

Chart.js Line graph y-axis not starting from 0

This is my current line graph. The x-axis is just a mock data so hope u guys can overlook the bad data used. As you can see on the y-axis, it is starting from 60 which is not what i want. I have tried beginAtZero = true but its not working. I would also like to remove the label weight but by simply removing not putting the labels, it would say undefined.
Below is the code for the line graph.
import React from 'react'
import {Line} from 'react-chartjs-2'
function LineChart(datasets) {
const dataset = datasets.data
return (
<div>
<Line
data={{
labels: dataset.map(data=> data.created_at),
datasets: [{
label: 'Weight',
data: dataset.map(data => data.weight),
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderWidth: 1,
borderColor: 'rgb(255, 99, 132)',
}]
}}
height = {200}
options = {{
resposive: true,
maintainAspectRatio: true,
scales: {
yAxes: [{
ticks: {
min: 0,
beginAtZero: true,
}
}]
}
}}
/>
</div>
)
}
export default LineChart
It seems that you're using Chart.js version 3, where the scales option needs to be defined differently (see Chart.js documentation).
options = {{
resposive: true,
maintainAspectRatio: true,
scales: {
y: {
beginAtZero: true
}
}
}}

Why are some react-chartjs-2 options being ignored?

I have this simple line chart that I am trying to change the gridlines from their default gray, however the options object appears to be selectively working. Maybe I am missing something basic but I have been fiddling with it for hours and cannot get it to work, any help is appreciated! I am using "react-chartjs-2".
Below is my render() method where I pass the data and options.
render() {
const data = {
labels: this.state.realTimes,
datasets: [
{
label: "Price",
data: this.state.Prices,
fill: false,
backgroundColor: "rgb(255, 255, 255)",
borderColor: "rgba(255, 255, 255)"
}
]
};
const options = {
scales: {
yAxis: {
beginAtZero: true, //this works
gridLines: {
color: "rgba(171,171,171,1)", //this doesn't
lineWidth: 0.5
}
}
}
};
return (
<div>
{this.state.loading ? (
this.loading()
) : (
<Line data={data} options={options} width={600} height={160} />
)}
</div>
);
}
Change scales.yAxis.gridLines to scales.yAxis.grid and it will work.
see Grid Line Configuration from Chart.js documentation or the Grid Configuration samples page.
Please take a look at below runnable JavaScript code and see how it works.
Please take a look at
new Chart('line-chart', {
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G'],
datasets: [{
label: 'My Dataset',
data: [65, 59, 80, 81, 56, 55, 40],
fill: false,
borderColor: 'rgb(75, 192, 192)',
tension: 0.2
}]
},
options: {
scales: {
yAxis: {
beginAtZero: true,
grid: {
color: 'rgb(0 ,0 ,255)',
lineWidth: 0.5
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.1/chart.min.js"></script>
<canvas id="line-chart" height="100"></canvas>
React chart.js is not up to date with chart.js so you can't use v3. Please use the v2 syntax since that is what react-chartjs uses.
https://www.chartjs.org/docs/2.9.4/axes/styling.html#grid-line-configuration
If you change yAxes: {gridLines: {color: 'red'}} to yAxes: [{gridLines: { color: 'red'}}] it should work as intended

Resources