Chart.js - Increase space between y Axes and the first column bar - reactjs

I am trying to give space between the first represented data bar and the yAxes.
Working example:
https://codesandbox.io/s/gracious-breeze-sc4zb?file=/src/App.js
Expected behaviour: (trying to add padding where the red is)

You can add an empty data and field to the dataset or you can use the padding.
Extra field:
var options = {
type: 'bar',
data: {
labels: ["", "Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [null, 12, 19, 3, 5, 2, 3],
backgroundColor: 'pink'
}]
},
options: {}
}
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>
Padding with cros alight start:
var options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'orange'
}]
},
options: {
scales: {
y: {
ticks: {
padding: 20,
crossAlign: 'start'
}
}
}
}
}
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>

Related

Chart.js Scale Y- axis ticks text alignment center

I have a question. I want to center the alignment of the text displayed on Yaxis in Chart.js, how can I do it? I don't think the official document has that content.
document link : https://www.chartjs.org/docs/latest/axes/styling.html#tick-configuration
my chart.js version : 3.8
as
to be
You can set crossAlign to 'far' in the tick options:
const 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: {
crossAlign: 'far'
}
}
}
}
}
const 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.8.0/chart.js"></script>
</body>

How do I create a stacked horizontal bar chart with Chart.js in React?

I'm really struggling to find a clear answer to this question - especially in React. I'd like to create a stacked horizontal bar chart component for my React application. This is the type of chart I'm trying to create: https://codepen.io/pen. The code pasted below is what I've tried to use so far but it isn't rendering currently.
import React, { Component } from 'react';
import Chart from 'chart.js/auto';
export default class LineChart extends Component {
chartRef = React.createRef();
componentDidMount() {
const ctx = this.chartRef.current.getContext('2d');
new Chart(ctx, {
type: 'bar',
data: {
labels: [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
],
},
options: {
scales: {
yAxes: [
{
stacked: true,
},
],
},
},
datasets: [
{
data: [86, 114, 106, 106, 107, 111, 133],
label: 'Total',
borderColor: '#3e95cd',
backgroundColor: '#7bb6dd',
// fill: False,
},
{
data: [70, 90, 44, 60, 83, 90, 100],
label: 'Accepted',
borderColor: '#3cba9f',
backgroundColor: '#71d1bd',
// fill: False,
},
{
data: [10, 21, 60, 44, 17, 21, 17],
label: 'Pending',
borderColor: '#ffa500',
backgroundColor: '#ffc04d',
// fill: False,
},
{
data: [6, 3, 2, 2, 7, 0, 16],
label: 'Rejected',
borderColor: '#c45850',
backgroundColor: '#d78f89',
// fill: False,
},
],
});
}
render() {
return (
<div>
<canvas id="myChart" ref={this.chartRef} />
</div>
);
}
}
You are using V2 syntax of Chart.js while using V3. V3 has major breaking changis inclusing all scales are their own object. For all changes please read the migration guide.
When using objects for scales you get what you want:
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'orange'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
backgroundColor: 'pink'
}
]
},
options: {
scales: {
y: {
stacked: true
},
x: {
stacked: true
}
}
}
}
const 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.7.1/chart.js"></script>
</body>

Resizable/Expendable box annotation in ChartJs

I am using chartjs-plugin-annotation in chartJs with ReactJs. But in box annotation is there a way how can I resize the box so I can expend the min, max value of the annotation.
My option code: `
options: {
scales: {
y: {
beginAtZero: true
}
},
plugins: {
autocolors: false,
annotation: {
annotations: {
box1: {
type: "box",
xMin: 1,
xMax: 2,
yMin: 5,
yMax: 10,
backgroundColor: "rgba(255, 99, 132, 0.25)"
}
}
}
}
}
`
Here is my code sandbox ReactJs-ChartJs
Yes, you can dive into the options part of your chart object, adjust the config for your annotation and then call chart.update() this will update the annotation.
Example:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1
}]
},
options: {
plugins: {
annotation: {
annotations: {
box1: {
type: "box",
xMin: 1,
xMax: 2,
yMin: 5,
yMax: 10,
backgroundColor: "rgba(255, 99, 132, 0.25)"
}
}
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
document.getElementById("tt").addEventListener("click", () => {
chart.options.plugins.annotation.annotations.box1.yMax = 16;
chart.update();
});
document.getElementById("rr").addEventListener("click", () => {
chart.options.plugins.annotation.annotations.box1.yMax = 8;
chart.update();
});
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<button id="tt">Update annotation to 16</button>
<button id="rr">Update annotation to 8</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.0/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-annotation/1.0.2/chartjs-plugin-annotation.js"></script>
</body>

Destroying Chart js within useEffect - React

I am having trouble destroying the previous chart when the a new chart is created.
The issue is that if if(myChart) myChart.destroy() never fires. Perhaps this is because the myChart variable only exists within the useEffect.
While the myChart variable could be allocated to a state, you wouldn't be able to call destroy() on a state directly.
So how would you go about this?
The below example renders a pie or a bar chart depending on the value of graphType:
import React, { useEffect } from "react";
import Chart from "chart.js";
export default function GraphMaker({ graphType }) {
useEffect(() => {
const ctx = document.getElementById("myChart");
if (myChart) myChart.destroy()
if (graphType === "pie") {
console.log(myChart)
var myChart = new Chart(ctx, {
type: "pie",
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "# of Votes",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
"Red",
"Blue",
"Yellow",
"Green",
"Purple",
"Orange"
],
borderColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
borderWidth: 1
}
]
}
});
}
else if (graphType === "bar") {
var myChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: "# of Votes",
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
"Red",
"Blue",
"Yellow",
"Green",
"Purple",
"Orange"
],
borderColor: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
borderWidth: 1
}
]
}
});
}
}, [graphType])
return (
<>
<canvas id="myChart" />
</>
);
}
In the new docs they also use this, they solved it by destroying the chart in the return of the use effect like this:
useEffect(() => {
const cfg = {
type: 'doughnut',
data: {
labels: [
'Red',
'Blue',
'Yellow'
],
datasets: [{
label: 'My First Dataset',
data: [300, 50, 100],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
'rgb(255, 205, 86)'
],
hoverOffset: 4
}]
}
};
const chart = new Chart(canvas.current.getContext('2d'), cfg);
return () => chart.destroy();
});
Link to their doc with live example: https://www.chartjs.org/docs/master/charts/doughnut/

Chartjs: make square legends

With react-chartjs-2, creating Bar Graph as below. I am trying to make the legends in square shape rather than default rectangle.
I applied boxWidth: 10 as below but it doesn't work, Is there any other possible alternatives to generate a square legend
const sample_data = {
labels: ['Item1', 'Item2'],
datasets: [
{
data: [10, 10, 50],
borderWidth: 1,
backgroundColor: 'yellow',
},
{ data: [20, 20, 20],
borderWidth: 1,
backgroundColor: 'green'
},
],
};
const sample_options = {
responsive: true,
legend: {
boxWidth: 10, // Also 0 doesn't make any change
},
...
};
<Bar data={sample_data} options={sample_options} />;
You will have to put the boxWidth in the labels part of the legend options as stated in the documentation: https://www.chartjs.org/docs/latest/configuration/legend.html#legend-label-configuration
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: {
legend: {
labels: {
boxWidth: 10
}
},
scales: {
yAxes: [{
ticks: {
reverse: false
}
}]
}
}
}
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/2.9.4/Chart.js" integrity="sha512-hZf9Qhp3rlDJBvAKvmiG+goaaKRZA6LKUO35oK6EsM0/kjPK32Yw7URqrq3Q+Nvbbt8Usss+IekL7CRn83dYmw==" crossorigin="anonymous"></script>
</body>

Resources