How to display text on both axis in react chart? - reactjs

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;

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>

Dynamically add x-axis in React using ChartJS

I want to add another x axis to my ChartJS which works, but the scales do not separate, for example I want one label on the x-axis with 0-9 and another one 0-16 to show separately. It works perfectly fine for the y-axis but not for the x-axis.
Now for the code:
here I create an initial state
let state = {
labels: [],
datasets: [
{
label: 'ignore',
fill: false,
lineTension: 0,
backgroundColor: 'rgba(109, 24, 172, 1)',
borderColor: 'rgba(109, 24, 172, 1)',
borderWidth: 0.1,
pointRadius: 0.2,
data: []
}, {
label: 'ignore1',
fill: false,
lineTension: 0,
backgroundColor: 'rgba(0, 250, 255, 1)',
borderColor: 'rgba(0, 250, 255, 1)',
borderWidth: 0.1,
pointRadius: 0.2,
data: []
}
]
};
Here is my first function with 9 datapoints:
function adddataset(){
let lineChart = Chart.instances[0];
const data=lineChart.data;
const newDataset = {
label: 'Dataset ' + (data.datasets.length + 1),
backgroundColor: 'rgba(109, 24, 172, 1)',
borderColor: 'rgba(0, 250, 255, 1)',
data: [65, 59, 80, 81, 56, 55, 40],
yAxisID: 'By',
xAxisID: 'Bx',
};
lineChart.data.datasets.push(newDataset);
lineChart.update();
}
here is my second function to add a second dataset:
function adddataset1(){
let lineChart = Chart.instances[0];
const data=lineChart.data;
const newDataset = {
label: 'Dataset ' + (data.datasets.length + 1),
backgroundColor: 'rgba(rgba(109, 24, 172, 1)',
borderColor: 'rgba(109, 24, 172, 1)',
data: [100,30,50,60,20,30,60,100,34,3456,6,5,4,3,5,545],
yAxisID: 'Cy',
xAxisID: 'Cx',
};
lineChart.data.datasets.push(newDataset);
lineChart.update();
}
now here is my class where I initialize the LineGraph and have 2 buttons which call the functions
class About extends React.Component {
render() {
return (
<body>
<main>
Graph
<div className='Graph'>
<div style={{ height: 500 }}>
<Line
id="mychart"
data={state}
options={{
title: {
display: true,
text: 'Average Rainfall per month',
fontSize: 20
},
legend: {
display: true,
position: 'right'
},
maintainAspectRatio: false,
responsive: true
}}
/>
</div>
</div>
<button onClick={adddataset1}>
Button1
</button>
<button onClick={adddataset}>
Button2
</button>
</main>
</body>
);
}
}
export default About;
There are 2 solutions for your problem, you can either provide your data in object format so the labels get taken from the object like so:
const data = [{x: '1', y: 5}, {x: '2', y: 3}];
Or you can add a second x axis with the correct ID to all the scales which has a labels array property in which you can specify the labels for that scale so you will get something like this:
const myChart = new Chart(ctx, {
type: 'line',
data: data,
options: options
});
myChart.options.scales['secondX'] = {
labels: ['6', '7', '8'],
position: 'bottom'
}
myChart.update();

How to add data to charts.js in react

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

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

Resources