How to display dynamic multiline graph using chart.js in reactjs - reactjs

I want to display a multiline graph for plan1 and plan2 with age on x-axis and totalnestegg on y-axis.
I have 4 array objects with age1 for plan1, totalnestegg1 for plan1, age2 for plan2 and totalnestegg2 for plan2.
I am able to display single plan but not mulitline.
age1 has items like [65,70,71,......,100] with corresponding amounts in totalamount1.
age2 has items like [70,71,72,......,100] with corresponding amounts in totalamount1.
I do know how to display labels for this kind, my current code looks like shown below:
import React from 'react';
import {Line} from 'react-chartjs-2';
export default class DisplayGraph extends React.Component {
state = {
labels: [],
datasets: [
{
label: 'Plan 1',
fill: true,
lineTension: 0,
backgroundColor: 'gray',
borderColor: 'gray',
borderWidth: 0,
data: this.props.totalNestEggForGraph1
},
{
label: 'Plan 2',
fill: true,
lineTension: 0,
backgroundColor: '#ccccff',
borderColor: 'gray',
borderWidth: 0,
data: this.props.totalNestEggForGraph2
}
]
}
render() {
return (
<div>
<Line
data={this.state}
options={{
title:{
display:true,
text:'Size of Retirement Savings',
fontSize:20
},
legend:{
display:true,
position:'right'
}
}}
/>
</div>
);
}
}

Related

react-chartjs-2 options are not recognized for Bars

I am trying to built a barchart component via "react-chartjs-2". I did pretty much paste my code from here: https://www.c-sharpcorner.com/article/create-different-charts-in-react-using-chart-js-library/.
This is how it looks:
import React from 'react';
import {Bar} from "react-chartjs-2";
const BarChart = () => {
const barChartData = {
labels: ["October", "November", "December"],
datasets: [
{
data: [8137119, 9431691, 10266674],
label: "Infected People",
borderColor: "#3333ff",
backgroundColor: "#547db4",
fill: true
},
{
data: [1216410, 1371390, 1477380],
label: "Deaths People",
borderColor: "#ff3333",
backgroundColor: "#f7813e",
fill: true
}
]
};
const barChart = (
<Bar
type="bar"
width={130}
height={50}
options={{
title: {
display: true,
text: "COVID-19 Cases of Last 3 Months",
fontSize: 15
},
legend: {
display: true, //Is the legend shown?
position: "bottom" //Position of the legend.
}
}}
data={barChartData}
/>
);
return barChart;
};
export default BarChart
Everything seems to be working fine, besides the fact that the options prop is not being recognized by the code.
Did anyone come across a similar issue and can help me out?
Update options prop as bellow.
options = {{
plugins: {
title: {
display: true,
text: "COVID-19 Cases of Last 3 Months"
},
legend: {
display: true,
position: "bottom"
}
}
}}

How to show data value on top of bar in react-chartjs-2?

I made bar chart in react-chartjs-2. I want to show data value of each bar on the top of the bar. For that I used the plugin calls chartjs-plugin-datalabels But it's not showing anything.
is it possible to show each value of bar chart ?
I want to show data value somethings like this.
Here is my code.
import React, { Component } from "react";
import "chartjs-plugin-datalabels";
import { Bar } from "react-chartjs-2";
export default class Button extends Component {
render() {
const dataBar = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: "#EC932F",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
const options = {
plugins: {
datalabels: {
display: true,
color: "black"
}
},
legend: {
display: false
}
};
return (
<div>
<Bar data={dataBar} options={options} width={100} height={50} />
</div>
);
}
}
Any help would be appreciated.
import React, { Component } from "react";
import Chart from "chart.js/auto";
import ChartDataLabels from "chartjs-plugin-datalabels";
import { Bar } from "react-chartjs-2";
export default class Button extends Component {
componentDidMount() {
Chart.register(ChartDataLabels);
}
render() {
const dataBar = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
backgroundColor: "#EC932F",
borderColor: "rgba(255,99,132,1)",
borderWidth: 1,
hoverBackgroundColor: "rgba(255,99,132,0.4)",
hoverBorderColor: "rgba(255,99,132,1)",
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
const options = {
plugins: {
datalabels: {
display: true,
color: "black",
formatter: Math.round,
anchor: "end",
offset: -20,
align: "start"
}
},
legend: {
display: false
}
};
return (
<div>
<Bar data={dataBar} options={options} width={100} height={50} />
</div>
);
}
}
Here you can see in componentDidMount we have registered chart data label plugin for displaying data.
And another thing is in the options added few more parameters as per below field
anchor: "end",
offset: -20,
align: "start"
This is used for displaying data in the top.
The react-chartjs-2 package holds a plugin property which can be set on the components.
Change the import from:
import "chartjs-plugin-datalabels";
to:
import ChartDataLabels from 'chartjs-plugin-datalabels';
On your component, add the plugin variable which holds the imported value.
from:
<Line data={data} options={options} />
to:
<Line data={data} plugins={[ChartDataLabels]} options={options} />
See this original stackoverflow answer to the similar question
use this "chartjs-plugin-datalabels": "^0.5.0" version
it works for me
Here is working example
https://codesandbox.io/s/barchart-knycb
const options2 = {
plugins: {
datalabels: {
anchor: "end",
align: "start",
formatter:(value,context)=>{
const datasetArray = []
context.chart.data.datasets.forEach((dataset)=>{
if(dataset.data[context.dataIndex] != undefined){
datasetArray.push(dataset.data[context.dataIndex])
}
})
function totalSum(total, datapoint){
return total + datapoint;
}
let sum = datasetArray.reduce(totalSum,0)
if(context.datasetIndex == datasetArray.length-1)
return sum
else
return ''
},
},
title: {
display: true,
text: 'Chart.js Bar Chart - Stacked',
},
},
responsive: true,
scales: {
x: {
stacked: true,
ticks: {
maxRotation: 70,
minRotation: 70
}
},
y: {
stacked: true,
},
},
};
const data1 = {
labels,
datasets: [
{
label: 'Dataset One',
data: [1,2,3,4,5,6,7],
backgroundColor: 'rgba(255, 99, 132, 0.5)',
},
{
label: 'Dataset Two',
data: [1,8,3,4,9,6,7],
backgroundColor: 'rgba(53, 162, 235, 0.5)',
},
],
};

React bizchart add axis name

Im using my react project for biz-chart , i have some conflict on the adding X and Y axis to name, anyone know how to added this correctly ?
here the image description
live sample code here
Thanks
code here
import React from "react";
import {
G2,
Chart,
Geom,
Axis,
Tooltip,
Coord,
Label,
Legend,
View,
Guide,
Shape,
Facet,
Util
} from "bizcharts#3.5.8";
import DataSet from "#antv/data-set";
class Groupedcolumn extends React.Component {
render() {
const data = [
{
name: "London",
"Jan.": 18.9,
"Feb.": 28.8,
"Mar.": 39.3,
"Apr.": 81.4,
May: 47,
"Jun.": 20.3,
"Jul.": 24,
"Aug.": 35.6
},
{
name: "Berlin",
"Jan.": 12.4,
"Feb.": 23.2,
"Mar.": 34.5,
"Apr.": 99.7,
May: 52.6,
"Jun.": 35.5,
"Jul.": 37.4,
"Aug.": 42.4
}
];
const ds = new DataSet();
const dv = ds.createView().source(data);
dv.transform({
type: "fold",
fields: ["Jan.", "Feb.", "Mar.", "Apr.", "May", "Jun.", "Jul.", "Aug."],
// 展开字段集
key: "月份",
// key字段
value: "月均降雨量" // value字段
});
return (
<div>
<Chart height={400} data={dv} forceFit>
<Axis name="月份" />
<Axis name="月均降雨量" />
<Legend />
<Tooltip
crosshairs={{
type: "y"
}}
/>
<Geom
type="interval"
position="月份*月均降雨量"
color={"name"}
adjust={[
{
type: "dodge",
marginRatio: 1 / 32
}
]}
/>
</Chart>
</div>
);
}
}
Can add a title to the Axis component
title={{
autoRotate: true, // 是否需要自动旋转,默认为 true
offset: 40, // 设置标题 title 距离坐标轴线的距离
textStyle: {
fontSize: '12',
textAlign: 'center',
fill: '#999',
fontWeight: 'bold',
},
position: 'center', // 标题的位置,**新增**
}}

Chartjs-2(React), Lines do not appear

When I console.log(this.state) in App.js, Object of data appear on devtool Browser but no change on screen.
No lines, no options, nothing.
When I console.log(this.state) in Chart.js, Object appear two time but always empty.
No error message for once, but it's not better.
I want create two lines, I don't know if it's the right way.
But I don't think problem comes from there
App.js
import React, { Component } from 'react';
import './style/App.css';
import axios from 'axios'
import Table from './components/table/Table'
import Chart from './components/Chart'
class App extends Component {
state = {
tabData: [],
chartData: {}
}
componentWillMount = () => {
this.getDataFromServer()
}
getDataFromServer = () => {
axios.get("http://localhost:8000")
.then((response) => {
const twentyObj = response.data.splice(0,20);
const time = twentyObj.map(item =>
item.timestamp
);
const cacData = twentyObj.map(item =>
item.stocks.CAC40
);
const nasData = twentyObj.map(item =>
item.stocks.NASDAQ
);
this.setState({
tabData:twentyObj,
chartData:{
labels: [time],
datasets:[
{ label:"CAC40",
data:[cacData],
fill: false,
lineTension: 0.1,
backgroundColor: 'rgba(75,192,192,0.4)',
borderColor: 'rgba(75,192,192,1)',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'rgba(75,192,192,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(75,192,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
},
{ label:"NASDAQ",
data:[nasData],
fill: false,
lineTension: 0.1,
backgroundColor: 'rgba(75,30,192,0.4)',
borderColor: 'rgba(75,30,192,1)',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'rgba(75,30,192,1)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(75,30,192,1)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
}
],
}
})
console.log(this.state)
})
.catch(function (error) {
console.log(error);
})
}
render() {
return (
<div className="App">
<h1>TEST Project</h1>
<Chart linesData={this.state.chartData}/>
<Table stateData={this.state.tabData}/>
</div>
);
}
}
export default App;
Chart.js
import React, { Component } from 'react';
import { Line } from 'react-chartjs-2';
class Chart extends Component{
state = {
chartLinesData:this.props.linesData
}
render(){
console.log(this.state)
return(
<Line data={this.state.chartLinesData}
width={300}
height={150}
options={{
maintainAspectRatio: false
}}
/>
)
}
}
export default Chart;
Try like this.. This works for me:
npm install --save react-chartjs-2 chart.js
In your page import things like:bar, line, etc as per requirement.
import { Doughnut, Bar, Line, Pie } from 'react-chartjs-2';
In constructor, fill datasets in the state:
this.state = {
lineChartData: {
labels: ['01', '02', '03', '04', '05', '06'],
datasets: [{
label: 'X',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
}
finally, call your component/graph in jsx:
<Line
data={this.state.lineChartData}
options={{ maintainAspectRatio: true }}
/>
Hope this works fine.

Is it possible to set up 0 as a minimum number for bar chart? react-chart.js-2

I'm trying to make a bar chart using react-chart.js-2. I just noticed that all bar chart example start from the minimum number of the data, not 0.
The example below, the bar chart starts from 40, not 0. What I want to do is to make a bar chart starting from 0, not the minimum number of the data.
Is it possible to make it using react-chart.js2?
Here is the code(mostly code from the official example )
import React from 'react';
import {Bar} from 'react-chartjs-2';
import 'chartjs-plugin-datalabels';
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label: 'My First dataset',
backgroundColor: 'rgba(255,99,132,0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1,
hoverBackgroundColor: 'rgba(255,99,132,0.4)',
hoverBorderColor: 'rgba(255,99,132,1)',
data: [65, 59, 80, 81, 56, 55, 40]
}
]
};
export default React.createClass({
displayName: 'BarExample',
render() {
return (
<div>
<h2>Bar Example (custom size)</h2>
<Bar
data={data}
width={150}
height={100}
/>
</div>
);
}
});
Here is a demo.
To start the y-axis from 0, you would have to set the beginAtZero property to true for y-axis ticks, in your chart options, like so :
options={{
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}}
see - working demo
You need to add this piece of code to the dataset object
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
}
}]
}
}
You can read more in the docs Axes Range setting

Resources