How to add data to charts.js in react - reactjs

Need your help. Component is already created for Bar chart as it is said in the documentations. Now want to add data to the Bar chart but it is not adding. The code is following
const data = {
type:"bar",
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [
{
label: 'Statistics',
data: [4, 10, 7, 1, 8, 9],
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: 4,
responsive: true,
},
],
};
const options = {
scales: {
YAxes: [
{
ticks: {
beginAtZero: 8,
},
},
],
},
};
const Dashboard = (props) => {
const addDatasets= ()=>{
const myChart= new Chart()
const newData= {
label:"Statistics of activity",
data:[8,10,9, 17,25, 31],
backgroundColor: [
"red",
],
borderColor: [
'blue',
],
borderWidth: 4,
}
data.datasets.push(newData)
myChart.update()
}
return (
<>
<div className='header'>
<h1 className='title'>Vertical Bar Chart</h1>
<div className='links'>
<a
className='btn btn-gh'
href='https://github.com/reactchartjs/react-chartjs-2/blob/master/example/src/charts/VerticalBar.js'
>
Github Source
</a>
</div>
</div>
<Bar data={data} options={options} />
<button onClick={addDatasets}>Add Datasets</button>
</>
);
};
Think that the problem is comming from this part
const myChart= new Chart()
in the internet can not find sources to solve the problem. What is the problem?

I used class component in the chartjs shared my usage in the below,
const options = {
scales: {
yAxes: [
{
ticks: {
beginAtZero: true,
},
},
],
},
};
#observer
export class Home extends React.Component<{}, IHomeState> {
constructor(props: any) {
super(props);
this.state = {
isReady: false,
isLoading: false,
data: {
labels: ["", ""],
datasets: [],
},
};
this.handleSelect = this.handleSelect.bind(this)
this.getKeywords = this.getKeywords.bind(this);
}
async getKeywords() {
this.setState({
isReady: false,
data: {
datasets:[],
labels:[]
},
isLoading: true,
})
let labels: string[] = []
const data = {
labels: ['', ''],
datasets: [],
} as any;
try {
let graphData1: DocumentResponseModel[] = await BaseMapper.mapToGraphData();
//How many types of the result / positives,negatives and mixed
graphData1.forEach((item: DocumentResponseModel) => {
if (!labels.includes(item.sentiment)) {
labels.push(item.sentiment)
}
})
this.setState({
isReady: true,
isLoading: false,
data: {
labels: "first","second"],
datasets: data.datasets
},
})
} catch (e) {
alert(e)
}
}
async componentDidMount() {
}
render() {
let {isReady, isLoading} = this.state;
const renderLoading = () => {
if (!isReady && isLoading) {
return (
<CircleToBlockLoading/>
)
} else {
return
}
}
return (
<div className={styles.container}>
<Button variant="contained" onClick={this.getKeywords} color="primary">Get</Button>
<Bar data={this.state.data} options={options} type={"bar"}/>
</div>
);
}
}

Related

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>

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

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 tooltip on legend hover?

I am using chart.js in React.
I have read and implemented:
Chart.js - show tooltip when hovering on legend
Unfortunately, this is not providing the desired results. I believe this is because this is being implemented in javascript, and I am implementing react. Not sure if that is impacting anything.
const data = {
labels: ['One', 'Two', 'Three'],
datasets: [{
data: [4, 5, 3],
backgroundColor: ['rgba(255, 99, 132, 0.2)', 'rgba(255, 159, 64, 0.2)', 'rgba(54, 162, 235, 0.2)'],
borderColor: ['rgb(255, 99, 132)', 'rgb(255, 159, 64)', 'rgb(54, 162, 235)'],
hoverBackgroundColor: ['rgba(255, 99, 132, 0.4)', 'rgba(255, 159, 64, 0.4)', 'rgba(54, 162, 235, 0.4)'],
borderWidth: 1,
hoverBorderWidth: 3
}]
};
const options = {
plugins: {
legend: {
onHover: (evt: any, legendItem: any, legend: any) => {
const index = legend.chart.data.labels.indexOf(legendItem.text);
const activeSegment = legend.chart.getDatasetMeta(0).data[index];
// console.log(activeSegment);
// activeSegment.options.backgroundColor = activeSegment._options.hoverBackgroundColor;
// activeSegment.options.borderWidth = activeSegment._options.hoverBorderWidth;
legend.chart.tooltip._active = [activeSegment];
legend.chart.update();
legend.chart.draw();
},
onLeave: (evt: any, legendItem: any, legend: any) => {
const index = legend.chart.data.labels.indexOf(legendItem.text);
// const activeSegment = legend.chart.getDatasetMeta(0).data[index];
// activeSegment.options.backgroundColor = activeSegment._options.backgroundColor;
// activeSegment.options.borderWidth = activeSegment._options.borderWidth;
legend.chart.tooltip._active = [];
legend.chart.update();
legend.chart.draw();
}
},
},
}
with the end of this component returning the following:
return <Doughnut data={data} options={options} />;
This produces the chart that is shown in the stackoverflow post that I linked.
For v3 you can use an method to set the tooltip programatically
onHover: (evt, item, legend) => {
const chart = legend.chart;
const tooltip = chart.tooltip;
const chartArea = chart.chartArea;
tooltip.setActiveElements([{
datasetIndex: 0,
index: item.index,
}], {
x: (chartArea.left + chartArea.right) / 2,
y: (chartArea.top + chartArea.bottom) / 2,
});
chart.update();
},

How to display text on both axis in react chart?

I am new to react and I wanted to create a chart to display skill level. Where I wanted to display text on both X-axis and Y-axis. I have created bar/line and pie chart using React.js. Currently I am able to display digit on -axis and text on X-axis. However, is there a way to display string(text) on both axis?
I would like to display ["Expert", "Advanced", "Intermediate", "Beginner"] on Y-axis and on X-axis, I would like to display - ["HTML", "CSS", "React JS", "Javascript", "SQL","Drupa].
I am using 'react-chartjs-2' module (https://gor181.github.io/react-chartjs-2/).
I have created component called 'Chart.jsx' and code for that is:
import React, { Component } from "react";
import { Bar, Line, Pie } from "react-chartjs-2";
import "./Chart.css";
class Chart extends Component {
constructor(props) {
super(props);
this.state = {
chartData: props.chartData
};
}
static defaultProps = {
displayTitle: true,
DisplayLegend: true,
LegendPosition: 'right',
level:'Skills'
};
render() {
return (
<div className="chart">
<Bar
data={this.state.chartData}
options={{
title: {
display: this.props.displayTitle,
text: 'Skills I am proficient with '+this.props.level,
},
legend: {
display: this.props.DisplayLegend,
position: this.props.LegendPosition
}
}}
/>
<Line
data={this.state.chartData}
options={{
title: {
display: this.props.displayTitle,
text: 'Skills I am proficient with '+this.props.level,
},
legend: {
display: this.props.DisplayLegend,
position: this.props.LegendPosition
}
}}
/>
<Pie
data={this.state.chartData}
options={{
title: {
display: this.props.displayTitle,
text: 'Skills I am proficient with '+this.props.level,
},
legend: {
display: this.props.DisplayLegend,
position: this.props.LegendPosition
}
}}
/>
</div>
);
}
}
export default Chart;
I have created one page called 'Skills.jsx' and code for that is:
import React, { Component } from "react";
import Navbar from "../components/Navbar.jsx";
import Footer from "../components/Footer.jsx";
import Jumbotron from "../components/Jumbotron.jsx";
import Chart from "../components/Chart.jsx";
class Skills extends Component {
constructor() {
super();
this.state = {
chartData: {}
};
}
componentWillMount() {
this.getChartData();
}
getChartData() {
//Ajax calls here
this.setState({
chartData: {
labels: [
"HTML",
"CSS",
"React JS",
"Javascript",
"SQL",
"Drupal"
],
datasets: [
{
// labels: "Level",
labels: ["Expert", "Advanced", "Intermediate", "Beginner"],
data: [100, 90, 90, 70, 60, 50, 40, 30, 20, 10, 0],
//labels: ["Expert", "Advanced", "Intermediate", "Beginner"],
displays: ["Expert", "Advanced", "Intermediate", "Beginner"],
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)",
"rgba(153, 102, 235, 0.6)",
"rgba(255, 159, 132, 0.6)",
"rgba(255, 99, 132, 0.6)"
]
}
]
}
});
}
render() {
return (
<div>
<Navbar />
<Jumbotron title="welcome" subtitle="put something" />
<div className="container">
<h2>My Skills</h2>
<p>Look, what I can do ..</p>
</div>
<div>
<Chart chartData={this.state.chartData} lavel="HTML" LegendPosition="bottom" />
</div>
<Footer />
</div>
);
}
}
export default Skills;
Thank you in advance!
you need to use scales title inside the options
options = {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Y text'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'X text'
}
}],
}
}
Here, is my code of using 'scales title' and 'ticks' to display text on both axis in react chart. Hope that helps others!
on 'Chart.jsx' file:
import React, { Component } from "react";
import { Bar, Line, Pie } from "react-chartjs-2";
import "./Chart.css";
class Chart extends Component {
constructor(props) {
super(props);
this.state = {
chartData: props.data,
chartOptions: props.options
};
}
static defaultProps = {
displayTitle: true,
DisplayLegend: true,
LegendPosition: "right",
level: "Skills",
data: {
labels: ["HTML", "CSS", "Javascript", "Drupal", "ReactJS", "SQL"],
datasets: [
{
data: [90, 90, 60, 70, 25, 65, 100, 55, 80, 40, 30, 40, 10, 0],
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)",
"rgba(153, 102, 235, 0.6)",
"rgba(255, 159, 132, 0.6)",
"rgba(255, 99, 132, 0.6)"
]
// label: 2015
}
/* {
data: [90, 90, 60, 70, 60, 70, 100, 55, 80, 40, 30, 20, 10, 0],
backgroundColor: "#FF7",
label: 2016
}*/
]
},
options: {
scales: {
yAxes: [
{
ticks: {
callback: function(label, index, labels) {
console.log("label is: " + label);
if (label > 75) {
return "Expert: " + label;
} else if (label > 50) {
return "Advanced: " + label;
} else if (label > 25) {
return "Intermediate: " + label;
} else {
return "Beginner: " + label;
}
// return '$' + label;
}
}
}
]
}
}
};
render() {
return (
<Bar data={this.state.chartData} options={this.state.chartOptions} />
);
}
}
export default Chart;
and on skills.jsx page-
import React, { Component } from "react";
import Navbar from "../components/Navbar.jsx";
import Footer from "../components/Footer.jsx";
import Jumbotron from "../components/Jumbotron.jsx";
import Chart from "../components/Chart.jsx";
class Skills extends Component {
constructor() {
super();
this.state = {
chartData: {}
};
}
componentWillMount() {
this.getChartData();
}
getChartData() {
//Ajax calls here
this.setState({
chartData: {
labels: [
"HTML",
"CSS",
"React JS",
"Javascript",
"SQL",
"Drupal"
],
datasets: [
{
// labels: "Level",
labels: ["Expert", "Advanced", "Intermediate", "Beginner"],
data: [90, 90, 40, 40, 60, 80, 40, 30, 20, 10, 0, 100],
//labels: ["Expert", "Advanced", "Intermediate", "Beginner"],
displays: ["Expert", "Advanced", "Intermediate", "Beginner"],
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)",
"rgba(153, 102, 235, 0.6)",
"rgba(255, 159, 132, 0.6)",
"rgba(255, 99, 132, 0.6)"
]
}
]
}
});
}
render() {
return (
<div>
<Navbar />
<Jumbotron title="welcome" subtitle="put something" />
<div className="container">
<h2>My Skills</h2>
<p>Look, what I can do ..</p>
</div>
<div>
<Chart chartData={this.state.chartData} lavel="HTML" LegendPosition="bottom" />
</div>
<Footer />
</div>
);
}
}
export default Skills;

Resources