Chartjs-2(React), Lines do not appear - reactjs

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.

Related

React react-chartjs-2 adding x and y axis labels to a line graph

import React from "react";
import { Line } from "react-chartjs-2";
// "chart.js": "^2.9.4",
// "react-chartjs-2": "^2.11.1"
const ext_data = [11, 19, 3, 5, 2, 3, 14, 19];
const ll = Array.from(Array(ext_data.length).keys());
const data = {
labels: ll,
datasets: [
{
label: "Profit$",
data: ext_data,
fill: false,
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgba(255, 99, 132, 0.4)"
}
]
};
const options = {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true
}
}
]
}
};
const LineChart = () => (
<>
<div className="header">
<h1 className="title">Profit Trend</h1>
<div className="links"></div>
</div>
<Line data={data} options={options} />
</>
);
export default LineChart;
I am trying to add x-axis name : "time" and y-axis name: "number of cars".
I went into the documentation : https://www.chartjs.org/docs/latest/axes/labelling.html
However, I was not able to find something that was useful.
Thank you for your time.
In react-chartjs-2, to add your title to your axis, just add this to your yAxes array of options (options.scales.yAxes[]):
scaleLabel: {
display: true,
labelString: "number of cars",
fontColor: "color you want",
}
same for your xAxes.

Chart.js with React. Multiple labels for multiple data-setsData from axios

I am using chart.js in React to create Line charts. I have to show data of the 10 days, 6 months and 1 year. For the days I have different labels and data, for the months I have different labels and data and so on. How do I replace this whole canvas with the plot for other data?
My Github repository: https://github.com/weronikamichalczewska/kursy-walut
API documentation: https://api.nbp.pl/en.html
There is also a 'problem' with api for showing 10 days I am using this address now: http://api.nbp.pl/api/exchangerates/rates/a/usd/last/10/?format=json
But to show data from the last year you have to use:
https://api.nbp.pl/api/exchangerates/rates/a/usd/2021-08-26/2022-08-27/?format=json
Anyone have any ideas on how to solve this?
Please help I'm beginner. Here is my code.
import axios from 'axios';
import { useParams } from 'react-router-dom';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend
);
const rate = axios.create({
baseURL: 'http://api.nbp.pl/api/exchangerates/rates/a/',
});
const Chart = () => {
const [post, setPost] = useState();
const { id } = useParams();
useEffect(() => {
async function getPost() {
const response = await rate.get(`/${id}/last/10/?format=json`);
setPost(response.data);
}
getPost();
}, [id]);
const label = ['10 days', '6 months', '1 year'];
const data = {
type: 'line',
labels: post?.rates?.map((x) => {
const date = new Date(x.effectiveDate);
return new Intl.DateTimeFormat('pl', {
month: 'short',
day: 'numeric',
}).format(date);
}),
datasets: [
{
label: label[0],
data: post?.rates?.map((y) => y.mid),
lineTension: 0.1,
backgroundColor: 'rgba(15, 174, 150)',
borderColor: 'rgba(15, 174, 150)',
gridLines: 'false',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'rgba(15, 174, 150)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(15, 174, 150)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
},
{
label: label[1],
data: post?.rates?.map((y) => y.mid),
lineTension: 0.1,
backgroundColor: 'rgba(15, 174, 150)',
borderColor: 'rgba(15, 174, 150)',
gridLines: 'false',
borderCapStyle: 'butt',
hidden: 'true',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: 'rgba(15, 174, 150)',
pointBackgroundColor: '#fff',
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: 'rgba(15, 174, 150)',
pointHoverBorderColor: 'rgba(220,220,220,1)',
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
},
],
options: {
responsive: true,
},
};
return (
<div
style={{
width: '800px',
height: '800px',
margin: '0px auto',
paddingTop: '500px',
}}
>
<Line data={data} />
</div>
);
};
export default Chart;

How to style the axis label for a bar chart using React-chartjs-2

bar-chart
I have to make a bar chart like in the photo above which has rounded corners with a linear gradient background and the x-axis label should also have a background and rounded corners using react-chartjs-2
My current code is:
Chart.js
import React from "react";
import { Bar } from "react-chartjs-2";
function Chart(props) {
return (
<div className="chart" style={{ width: "15rem", height: "15rem" }}>
<Bar
data={props.chartData}
options={{
ticks: {
stepSize: 25,
max: 100,
},
plugins: {
legend: {
display: false,
}
},
maintainAspectRatio: false,
borderRadius: 5,
scales: {
x: {
grid: {
display: false
}
},
y: {
grid: {
display: false
}
}
},
}}
/>
</div>
);
}
export default Chart;
And props received by this component are :
state = {
chartData: {}
};
componentWillMount() {
this.getChartData();
}
getChartData() {
this.setState({
chartData: {
labels: ["Age 5", "Age 10", "Age 15", "Age 35"],
datasets: [
{
data: [2, 15, 27, 100],
//backgroundColor:'green',
backgroundColor: [
"rgba(255, 99, 132, 0.6)",
"rgba(54, 162, 235, 0.6)",
"rgba(255, 206, 86, 0.6)",
"rgba(75, 192, 192, 0.6)",
]
}
]
}
});
}

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)',
},
],
};

Is there a way to add a drop shadow for one specific line in the line chart containing many lines?

I am trying to add a drop shadow for one specific line in the chart.
This helped somehow but was not enough:
https://stackoverflow.com/a/33124653/4500286
I am using the package of "react-chartjs-2": "2.7.6" in a react project.
What I came up with, adds a drop shadow for all the lines .. I can't seem to find a way to add it per dataset.
I have prepended this code to the componentWillMount that adds a drop shadow to all the lines (which isn't what I want)
Chart.pluginService.register({
id: 'dropShadow',
afterDraw: function (chart, easing) {
console.log(chart);
let originial = this;
const { ctx } = chart;
let originalStroke = ctx.stroke;
ctx.stroke = function () {
ctx.save();
ctx.shadowColor = '#C4A4BF';
ctx.shadowBlur = 7;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
originalStroke.apply(this, arguments)
ctx.restore();
}
}
});
This is a mini sample of the code I'm tried to build
import React from 'react';
import mediaPlanner from '../api/mediaPlanner';
import {Line,Chart} from "react-chartjs-2";
class Revenue extends React.Component{
constructor(props){
super(props);
this.state = {
data: {}
}
this.graphDataSample = {
forecastRevenue: ["3000", "3500", "3500"]
revenue: ["1000", "3000", "5000"]
timestamp: ["2019-02-01", "2019-02-02", "2019-02-03"]
}
// get up the options of the graph
this.options = {
maintainAspectRatio: false,
legend: {
display: true,
position: 'bottom',
labels: {
fontColor: 'rgb(255,255,255)',
}
},
tooltips: {
backgroundColor: "#f5f5f5",
titleFontColor: "#333",
bodyFontColor: "#666",
bodySpacing: 4,
xPadding: 12,
mode: "nearest",
intersect: 0,
position: "nearest"
},
responsive: true,
scales: {
yAxes: [
{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: "rgba(29,140,248,0.0)",
zeroLineColor: "transparent"
},
ticks: {
suggestedMin: 60,
suggestedMax: 125,
padding: 20,
fontColor: "#9a9a9a"
}
}
],
xAxes: [
{
barPercentage: 1.6,
gridLines: {
drawBorder: false,
color: "rgba(29,140,248,0.1)",
zeroLineColor: "transparent"
},
ticks: {
padding: 20,
fontColor: "#9a9a9a"
}
}
]
}
};
}
componentWillMount = () => {
// supposed to make an api call to get the data returned
// by graphDataSample
// adds the drop shadow to both revenue and forecast revenue
// I only want to add it to the forecast revenue
Chart.pluginService.register({
id: 'dropShadow',
afterDraw: function (chart, easing) {
console.log(chart);
let originial = this;
const { ctx } = chart;
let originalStroke = ctx.stroke;
ctx.stroke = function () {
ctx.save();
ctx.shadowColor = '#C4A4BF';
ctx.shadowBlur = 7;
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
originalStroke.apply(this, arguments)
ctx.restore();
}
}
});
this.setState({data: function(canvas){
return {
labels: this.graphDataSample.timestamp, // X-axis
datasets: [
{
fill: false,
borderColor: "#6C6C74",
borderWidth: 3,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: "#6C6C74",
pointHoverRadius: 0,
pointHoverBorderWidth: 10,
pointBorderWidth: 0,
steppedLine: false,
pointRadius: 0,
label: "Revenue ($)",
data: this.graphDataSample.revenue, // Y-axis
},
{
fill: false,
borderColor: "red",
borderWidth: 3,
borderDash: [],
borderDashOffset: 0.0,
pointBackgroundColor: "red",
pointHoverRadius: 0,
pointHoverBorderWidth: 10,
pointBorderWidth: 0,
steppedLine: false,
pointRadius: 0,
label: "Forecast Revenue ($)",
data: this.graphDataSample.forecastRevenue, // Y-axis
}
]
};
}});
}
render() {
return (
<Line
data={this.state.data}
options={this.options}
/>
);
}
}
export default Revenue;
As said the expected is to add a drop shadow to one line in my case is for the forecast revenue and not the revenue
That's a screenshot https://drive.google.com/file/d/1LjLyXEPGlgqlE1AziUQdf0GZJptwVEyf/view?usp=sharing

Resources