Dynamically add x-axis in React using ChartJS - reactjs

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

Related

react-chart-2 multi x axis

I am using react-chart-2 Line to show graph;
What i want is to have 2 line in the same graph but instead of multiple value in y axis i want the same y axis but different label; example i have these label
const colors = ['red', 'yellow', 'blue', 'green', 'pink'];
const sharpe = ['circle', 'square']
and i have these value:
const colorsData = [10, 5, 8, 9, 7]
const sharpeData = [17, 2]
in my options scale i have
scales: {
x: {
grid: {
drawOnChartArea: false,
},
position: 'bottom' as const;
labels: colors
},
x1: {
grid: {
drawOnChartArea: true,
},
position: 'top' as const,
labels: sharpe,
},
y: {
beginAtZero: true,
ticks: {
maxTicksLimit: 5,
stepSize: 5,
},
},
},
and in my data i have
{
labels: colors,
datasets: [
{
backgroundColor: 'rgba(0, 0, 0, 0.2)',
borderColor: 'rgba(13, 202, 240, 1)',
pointHoverBackgroundColor: '#fff',
borderWidth: 1,
data: colorsData,
xAxisId: 'x'
},
{
backgroundColor: 'rgba(0, 0, 0, 0.2)',
borderColor: 'rgba(202, 13, 240, 1)',
pointHoverBackgroundColor: '#fff',
borderWidth: 1,
data: sharpeData,
xAxisId: 'x1',
}
]
}
the expected result is that i have 2 x axis , in the bottom is the colors and in the top the sharpe; one y axis; and the two line will be drawed but the colors depends on colorsData value and the sharpe depends on sharpeData value.
But instead the colors line is drawed as expected but the sharpe line follow the colors label instead of sharpe label
What you are trying to achieve is not possible. The values of the top and bottom axis should be the same. Unless you stack two charts on top of one another with css.
You can only have the same labels for both axis x and x1 or y and y1 respectively.
This is the official docs on Charts.js for y axis.
https://www.chartjs.org/docs/latest/samples/line/multi-axis.html
Here is some code to give you an idea of what I have come to with top and bottom x axis:
Options:
const config = {
type: 'line',
data: data,
options: {
responsive: true,
interaction:{
mode: "index",
intersect: false,
},
stacked: false,
scales: {
x:{
type: "linear",
display: true,
position: "bottom",
},
x1:{
type: "linear",
display: true,
position: "top",
grid: {
drawOnChartArea: false,
},
},
},
},
};
Data:
const colors = ['red', 'yellow', 'blue', 'green', 'pink'];
const sharpeData = [17, 2, 9, 12 ,3];
const colorsData = [10, 5, 8, 9, 7];
const data = {
labels: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
datasets: [
{
label: "Colors",
backgroundColor: 'rgba(0, 0, 0, 0.2)',
borderColor: 'rgba(13, 202, 240, 1)',
pointHoverBackgroundColor: '#fff',
borderWidth: 1,
data: colorsData,
xAxisId: 'x',
},
{
label: "Shape",
backgroundColor: 'rgba(0, 0, 0, 0.2)',
borderColor: 'rgba(202, 13, 240, 1)',
pointHoverBackgroundColor: '#fff',
borderWidth: 1,
data: sharpeData,
xAxisId: 'x1',
}
]
};
Hope this helps!

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

react-chartjs-2 how to set multiple background levels within a line chart

I have a set of data which will be displayed in a line chart. The X axis will have "days", Y axis will have values from 0 - 200.
I want the background of the chart to be "yellow" for values under 80, and "green" for values between 80-120, "red" for values higher than 120.
I've being reading the documentation but I couldn't find something similar, i've included a picture of how it should be.
Many thanks.
You can use chartjs-plugin-annotation and draw individual colored boxes as shown in the runnable code snippet below.
new Chart('chart', {
type: 'line',
data: {
labels: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
datasets: [{
label: 'My Dataset',
data: [60, 90, 130, 110, 100, 90, 80, 70, 80, 100],
backgroundColor: 'rgba(0, 0, 0, 0.2)',
borderColor: 'rgb(0, 0, 0)',
borderWidth: 1,
fill: false
}]
},
options: {
scales: {
yAxes: [{
ticks: {
min: 0,
stepSize: 20
},
gridLines: {
display: false
}
}],
xAxes: [{
gridLines: {
display: false
},
}]
},
annotation: {
annotations: [{
type: 'box',
yScaleID: 'y-axis-0',
yMin: 120,
yMax: 220,
borderColor: 'rgba(255, 51, 51, 0.25)',
borderWidth: 0,
backgroundColor: 'rgba(255, 51, 51, 0.25)',
},
{
type: 'box',
yScaleID: 'y-axis-0',
yMin: 80,
yMax: 120,
borderColor: 'rgba(0, 204, 0, 0.25)',
borderWidth: 0,
backgroundColor: 'rgba(0, 204, 0, 0.25)',
},
{
type: 'box',
yScaleID: 'y-axis-0',
yMin: 0,
yMax: 80,
borderColor: 'rgba(255, 255, 0, 0.25)',
borderWidth: 0,
backgroundColor: 'rgba(255, 255, 0, 0.25)',
}],
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/0.5.7/chartjs-plugin-annotation.js"></script>
<canvas id="chart" height="80"></canvas>

ReactJS - Labeling multi dimension array with chartJS-2

The chart below I'm trying to create:
I am trying to add labels to my chart but it's showing as undefined. When I enter
labels: ["1", "2", "3"],
it gives the variable '1' to all the 1st variables. Any help on this would be brilliant. Thank you
const DummyChart = () => (
<Doughnut data={data} options={options} width={360} height={360} />
);
const data = {
datasets: [
{
label: "Dummy 1",
data: [487, 189],
backgroundColor: ["rgba(0, 193, 189)"],
borderColor: ["rgba(0, 193, 189)"],
borderWidth: 1
},
{
label: "Dummy 2",
data: [236, 764],
backgroundColor: ["rgba(0, 135, 136)"],
borderColor: ["rgba(0, 135, 136)"],
borderWidth: 1
},
{
label: "Dummy 3",
data: [811, 189],
backgroundColor: ["rgba(0, 193, 189)"],
borderColor: ["rgba(0, 193, 189)"],
borderWidth: 1
}
]
};
const options = {
responsive: true,
legend: {
display: false
},
rotation: Math.PI,
circumference: Math.PI,
cutout: 50
};
export default DummyChart;
Have you tried using point Labels on the chart. Additional chart js contains a label plugin which allows for more customization.
You can install it using this - npm i chartjs-plugin-labels.
Heres a link to a few demo's - https://emn178.github.io/chartjs-plugin-labels/samples/demo/
As per react-chartjs-2 examples there is a separate key named labels for that. You also have to use the tooltips options so you will be able to customize your labels. See the working example I made below:
var Doughnut = reactChartjs2.Doughnut;
const DummyChart = () => ( <Doughnut data={data} options = {options} width={360} height={360} />);
const data = {
labels: [
'Dummy 1',
'Dummy 2',
'Dummy 3',
],
datasets: [{
data: [487, 1000],
backgroundColor: ["rgba(0, 193, 189)"],
borderColor: ["rgba(0, 193, 189)"],
borderWidth: 1
},
{
data: [236, 1000],
backgroundColor: ["rgba(0, 135, 136)"],
borderColor: ["rgba(0, 135, 136)"],
borderWidth: 1
},
{
data: [811, 1000],
backgroundColor: ["rgba(0, 193, 189)"],
borderColor: ["rgba(0, 193, 189)"],
borderWidth: 1
}
]
};
const options = {
responsive: true,
legend: {
display: false
},
rotation: Math.PI,
circumference: Math.PI,
cutout: 50,
tooltips: {
callbacks: {
label: function(item, data) {
return data.labels[item.datasetIndex] + ' ' + data.datasets[item.datasetIndex].data[0] + '/' + data.datasets[item.datasetIndex].data[1]
}
}
}
};
ReactDOM.render(
<DummyChart /> ,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src='https://unpkg.com/chart.js#2.6.0/dist/Chart.js'></script>
<script src='https://unpkg.com/react-chartjs-2#2.1.0/dist/react-chartjs-2.js'>
</script>
<div id='app'></div>

Resources