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

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} />

Related

react-chart2: Cannot read properties of undefined (reading 'map')

I'm trying to create a bar chart with react-chartjs-2, but I'm receiving error:
Cannot read properties of undefined (reading 'map').
It's the first time I'm trying to create a Chart and I'm wondering what should I write differently, what is causing this error.
import React, {useEffect} from 'react'
import styled from 'styled-components';
import {Bar} from 'react-chartjs-2';
const ChartDaily = ({dailyPrices, chartData, setChartData}) => {
const Chart = () => {
setChartData({
labels: ['Open', 'High', 'Low', 'Close', 'Volume'],
datasets: [{
label: 'price',
data : [1, 100, 1000, 10000],
backgroundColor: [
'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)',
],
borderColor: [
'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
}]
})
}
useEffect(() => {
Chart();
}, [])
return (
<StyledChart>
<h3>Daily Prices</h3>
<Bar
data={chartData}
options={{
responsive:true,
title: { text: "Daily Chart", display: true },
scales:{
yAxes:{
ticks:{
beginAtZero: true
}
}
}
}}
/>
</StyledChart>
)
}
compare your code with this working example and see what went wrong.
import React from 'react';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
import { Bar } from 'react-chartjs-2';
import faker from 'faker';
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
);
export const options = {
responsive: true,
plugins: {
legend: {
position: 'top' as const,
},
title: {
display: true,
text: 'Chart.js Bar Chart',
},
},
};
const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
export const data = {
labels,
datasets: [
{
label: 'Dataset 1',
data: labels.map(() => faker.datatype.number({ min: 0, max: 1000 })),
backgroundColor: 'rgba(255, 99, 132, 0.5)',
},
{
label: 'Dataset 2',
data: labels.map(() => faker.datatype.number({ min: 0, max: 1000 })),
backgroundColor: 'rgba(53, 162, 235, 0.5)',
},
],
};
export function App() {
return <Bar options={options} data={data} />;
}
demo
pay attention that all the examples of react-chartjs-2 written in Typescript so if you are working with jsx not tsx files you may need to check this question:
How do I convert TSX to JSX

Can't change the default color and font size of labels in react-chartjs-2

So I want to render a simple bar graph in my website, I am using react-chartjs-2 for the same but I can't seem to change the default fontsize or even the color of the x label and ylabels. I have gone through the other answers but none of them are working for me. I have been at it for the last 2 hours and I still can't figure out whats the problem.
Here is my code
import React from 'react'
import './model.css'
import {Bar} from 'react-chartjs-2'
function Model() {
const data = {
labels: ['red', 'blue', 'white', 'green'],
datasets: [
{
label: '# of days',
data: [6, 7, 2, 14],
backgroundColor: [
'rgba(255, 99, 132, 0.4)',
'rgba(54, 162, 235, 0.4)',
'rgba(255, 206, 86, 0.4)',
'rgba(75, 192, 192, 0.4)',
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
],
borderWidth: 1,
},
],
};
const options= {
legend: {
labels: {
fontColor: "blue",
fontSize: 18
}
},
scales: {
yAxes: [{
ticks: {
fontColor: "white",
fontSize: 18,
stepSize: 1,
beginAtZero: true
}
}],
xAxes: [{
ticks: {
fontColor: "white",
fontSize: 14,
stepSize: 1,
beginAtZero: true
}
}]
}
}
return (
<div className="model-container">
<Bar
data={data}
options={options}
/>
</div>
)
}
export default Model
I would asume you are using v3, in v3 the scales have been reworked in how you write them, you can read all changed in the migration guide, to know for sure where to put the options and how there name is you can just check the documentation itself
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1
}
]
},
options: {
scales: {
y: {
ticks: {
color: 'red',
font: {
size: 14,
}
}
},
x: {
ticks: {
color: 'red',
font: {
size: 14
}
}
}
}
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.js"></script>
</body>

How do I filter & update dates using react-chartjs-2

I am using React-Chartjs-2 on a project and am getting stuck on updating the filter of my chart. I am following along with the following demo, but this doesn't just the react one, but the vanilla version.https://www.youtube.com/watch?v=Gc5JF2TUG7o&t=679s # 16:32 is the update function to update the filtered dates on the chart. I am able to get the index of the date array, but my chart doesn't update. How am I able to access and update the labels and datasets value within the Line component?
import React from 'react';
import {Line} from 'react-chartjs-2'
function BarChart() {
const dates = ['2021-08-25', '2021-08-26','2021-08-27','2021-08-28', '2021-08-29', '2021-08-30','2021-08-31' ];
const datapoints =[1,2,4,9,12,15,16]
function filterData() {
const dates2 = [...dates];
console.log(dates2);
const startdate = document.getElementById('startdate');
const enddate = document.getElementById('enddate');
//get the index number in the array
const indexstartdate = dates2.indexOf(startdate.value);
const indexenddate = dates2.indexOf(enddate.value);
console.log(indexstartdate);
console.log(indexenddate);
//slice the array
const filterDate = dates2.slice(indexstartdate, indexenddate + 1);
//replace label in the chart
//HELP HERE!!!
}
return (
<div>
<div>
<Line id='myChart'
data={{
labels:dates,
datasets: [
{
label: 'Sales',
data:datapoints,
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,
},
],
}}
height={400}
width={400}
options={{maintainAspectRatio:false,
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
}
}
]
},
}}
/>
</div>
<input type='date' onChange={filterData} id='startdate' />
<input type='date' onChange={filterData} id='enddate' />
</div>
)
}
export default BarChart
You need to use the React state so your component will rerender. Here is my solution, I hope it helps.
import React, { useRef, useState } from "react";
import { Line } from "react-chartjs-2";
function BarChart() {
const initialDates = [
"2021-08-25",
"2021-08-26",
"2021-08-27",
"2021-08-28",
"2021-08-29",
"2021-08-30",
"2021-08-31",
];
const initialDataPoints = [1, 2, 4, 9, 12, 15, 16];
const [dates, setDates] = useState(initialDates);
const [dataPoints, setDataPoints] = useState(initialDataPoints);
console.log(dates, dataPoints);
const inputRef1 = useRef();
const inputRef2 = useRef();
function filterData() {
const dates2 = [...dates];
const dataPoints2 = [...dataPoints];
//slice the array
let value1 = inputRef1.current.value;
let value2 = inputRef2.current.value;
const indexstartdate = dates2.indexOf(value1);
const indexenddate = dates2.indexOf(value2);
console.log(indexstartdate);
console.log(indexenddate);
//slice the array
const filterDate = dates2.slice(indexstartdate, indexenddate + 1);
const filterDataPoints = dataPoints2.slice(
indexstartdate,
indexenddate + 1
);
console.log(filterDate, filterDataPoints);
//replace label in the chart
//HELP HERE!!!
setDates(filterDate);
setDataPoints(filterDataPoints);
console.log(dates, dataPoints);
}
return (
<div>
<div>
<Line
id="myChart"
data={{
labels: dates,
datasets: [
{
label: "Sales",
data: dataPoints,
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,
},
],
}}
height={400}
width={400}
options={{
maintainAspectRatio: false,
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
}}
/>
</div>
<input type="date" ref={inputRef1} />
<input type="date" ref={inputRef2} />
<button onClick={filterData}>Filter</button>
</div>
);
}
export default BarChart;

Calling a helper function and passing in data to chart.js

I created a helper function to work around my chart.js.
First, on my index.html file I put the ff:
<div id="app"></div>
<canvas id="myChart" width="400" height="400"></canvas>
Next, to call chart.js, I created a helper function with the necessary data/arguments on it:
export const chartUI = (labels, data) =>{
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: 'RATES',
data: data,
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
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
};
Now on my component where I need to put my data on I called the function so it can manipulate and display the data:
import React from 'react';
const helper = require('../../../helpers/utils')
const Chart = (props) => {
return(
<div>
{props.info.map(item => {
return <p>{helper.chartUI(item.time, item.rates)}</p>
}) }
</div>
)
};
export default Chart;
When I run this code i did not see any chart on the frontend and also I got this error: Uncaught TypeError: this.ticks.map is not a function The above error occurred in the <Chart> component: TypeError: this.ticks.map is not a function
PS. Here's the the type data I am flowing from my app:
{
"rates": [
{
"time": "2018-04-13T15:45:19.5968204Z",
"asset_id_quote": "$$$",
"rate": 4000000
},
{
"time": "2018-04-13T15:45:41.7725202Z",
"asset_id_quote": "1ST",
"rate": 37714.501225721289835941919668
}
}

reactjs charts implementation

I'm trying to implement a Line chart in my react app. I found this when searching for charts.
https://github.com/reactjs/react-chartjs
I have used this piece of code but it isn't clear how to use chartData and chartOptions
var LineChart = require("react-chartjs").Line;
var MyComponent = React.createClass({
render: function() {
return <LineChart data={chartData} options={chartOptions} width="600" height="250"/>
}
});
How can i declare the chartData and chartOptions inorder to get my Linechart work?
You need to define chartData and chartOptions as objects in your React Component. A sample chartData will look like
For a line Chart
var chartOptions: {
// Boolean - If we should show the scale at all
showScale: true,
// Boolean - Whether to show a dot for each point
pointDot: true,
showLines: false,
title: {
display: true,
text: 'Chart.js Bar Chart'
},
legend: {
display: true,
labels: {
boxWidth: 50,
fontSize: 10,
fontColor: '#bbb',
padding: 5,
}
}
var chartData = {
labels: [['Sunday', 'Monday'], ['Sunday', 'Tuesday']],
datasets: [
{
color: "#4D5360",
highlight: "#616774",
borderColor: "rgba(179,181,198,1)",
pointBackgroundColor: "rgba(179,181,198,1)",
pointBorderColor: "#fff",
pointHoverBackgroundColor: "#fff",
pointHoverBorderColor: "rgba(179,181,198,1)",
label: 'Current lag',
fill: false,
lineTension: 0.1,
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
scaleOverride: true, scaleStartValue: 0, scaleStepWidth: 1, scaleSteps: 30,
data: [[5, 8], [3, 11]]
}
]
}
For a barChart
var chartData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
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
}]
},
var chartOptions = {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
See the docs here for more information on the object properties:

Resources