How to create a bar and a line in a same graph using chart.js in React? - javascript

(Requirement: The bar has to start from the first tick(i.e label "a" below) in x axis whereas the line has to start from third tick(label "c" below)).
I have tried the following way.
import React from "react";
import Chart from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';
class Barchart extends React.Component {
//chart= null;
componentDidMount(){
this.configureChart();
}
configureChart = ()=>{
let bardata=[7, 3, 2];
let linedata=[ 0,0,0,75, 55, 80, 65];
// xaxislabel=["a","b","c"]
// xaxislabelline=["d","e","f","g"]
const node=this.node;
new Chart(node,{
plugins: [ChartDataLabels],
type:'',
data:{
datasets:[
{
yAxisID:'A',
label: "Bar Dataset",
data: bardata ,
type: "bar",
backgroundColor: "#DE924B",
order:1
},
{
yAxisID:'B',
label: "Line Dataset 2",
data: linedata,
type: "line",
fill: false,
borderColor: 'rgb(75, 192, 192)',
order:2
},
],
labels:["a","b","c","d","e","f","g"]
},
options:{
scales:{
yAxes:[
{ id:'A',
display:true,
ticks:{
beginAtZero:true
}
},
{ id:'B',
display:true,
ticks:{
beginAtZero:true
}
}
],
xAxes:[
{ id:'C',
display: true,
barThickness: 25,
ticks: {
beginAtZero: true,
}
},
{ id:'D',
display: true,
ticks: {
beginAtZero:true,
min:'c',
}
}
},
]
}
}
})
}
render(){
return(
<div>
<canvas
style={{ width: 650, height: 165 }}
ref={node => (this.node = node)}
/>
</div>
);
}
}
export default Barchart;
Below is the attached result I got.
I am not sure how to have the line graph start from label "c" of the main label(or have single label for both graphs).

Found the solution.
changed
let linedata=[ 0,0,0,75, 55, 80, 65]-->
let linedata=[ null,null,null,75, 55, 80, 65];

Related

How to add a title in Doughnut chart chart.js React

I want to add a Title for the Doughnut chart in my React app but for some reason it doesn't work. I have this code:
const chartData = {
labels: [],
datasets: [{
data: [],
backgroundColor: [
Colors.primary,
Colors.secondary,
Colors.danger,
Colors.warning
],
hoverBackgroundColor: [
'rgb(143, 0, 180, 0.3)',
'rgb(0, 196, 204, 0.3)',
'rgb(206, 0, 0, 0.3)',
'rgb(255, 179, 0, 0.3)'
],
hoverOffset: 10
}]
};
const options = {
responsive: true,
legend: {
display: false,
position: 'right',
},
title: {
display: true,
fontSize: 20,
text: 'Tickets'
}
}
<Doughnut
data = { chartData }
options = { options }
/>
What could have gone wrong here? I also want to place the labels on the right side of the chart, but it doesn't work as well. Below is the output.
Since Chart.js version 3 title, subtitle, legend and tooltip are plugins and their options must be defined in plugins node.
As far as I have seen, react-chartjs-2 is working with Chartjs version >= 3.
const options = {
responsive: true,
plugins: {
legend: {
display: false,
position: 'right',
},
title: {
display: true,
fontSize: 20, // <--- this is not a managed option since CHART.JS 3
text: 'Tickets'
}
}
}

options in Doughnut Chart error: Uncaught TypeError: Cannot read properties of undefined React

I use Doughnut chart form chart.js in React.
This code give me the error.
renderDoughnutChart(data, label) {
const chartData = {
labels: [],
datasets: [{
label: 'My First Dataset',
data: [],
backgroundColor: [
Colors.primary,
Colors.secondary,
Colors.danger,
Colors.warning
],
hoverBackgroundColor: [
'rgb(143, 0, 180, 0.3)',
'rgb(0, 196, 204, 0.3)',
'rgb(206, 0, 0, 0.3)',
'rgb(255, 179, 0, 0.3)'
],
hoverOffset: 30
}]
};
const options = {
responsive: true,
legend: {
display: false,
position: 'right',
},
title: {
display: true,
fontSize: 20,
text: 'My Title'
},
};
data.map((value) => {
if(value.value >= 0)
chartData.datasets[0].data.push(value.value)
else
chartData.datasets[0].data.push(0)
chartData.labels.push(value.label)
})
return (
<div style={{ width: '50%'}}>
<Doughnut
data = { chartData }
options = { options }
/>
</div>
)
}
Error:index.js:188 Uncaught TypeError: Cannot read properties of undefined (reading 'configMerge')
But if I don't pass the options = {options} to the Doughnut component, it works fine. What could cause the error?
Dependecy versions used:
chart.js: #3.3.0
react-chartjs-2: #2.9.0
Imports:
import { Chart } from "chart.js/auto"
import { Line, Doughnut } from 'react-chartjs-2'

Cannot find file: 'Chart.js' does not match the corresponding name on disk: '.\node_modules\chart.js\dist\chart.js'

i am trying to impliment a bar chart what am i doing wrong here?
here also i am getting error saying to use typescript
formatter: (value: number) => value + " %",
but i use only .js format
import { Chart } from "chart.js";
import { Bar } from "react-chartjs-2";
import ChartjsPluginStacked100 from "chartjs-plugin-stacked100";
import "chart.js/auto";
import ChartDataLabels from "chartjs-plugin-datalabels";
Chart.register(ChartDataLabels);
const ExampleChart = () => (
<Bar
data={{
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, 100],
borderRadius: 50, // Make Rectangle rounded
},
],
}}
options={{
indexAxis: "y", // Horizontal bar
plugins: {
datalabels: {
formatter: (value: number) => value + " %", // Add the percentage after the value
align: "end",
anchor: "end",
clip: true, // Hide label if outside of the chart
},
},
scales: {
x: {
grid: {
display: false, // Hide x grid
},
},
y: {
grid: {
display: false, // Hide y grid
},
},
},
}}
/>
);
export default function bar() {
return (
<div className="">
<ExampleChart />
</div>
);
}
Seems like you are using typings in .js file.
Remove Typings from your formatter function
formatter: (value) => value + " %", // Add the percentage after the value
Working StackBlitz

How to increase line chart width in ng2-charts?

I am trying to render a line chart using "ng2-charts": "^2.3.0" and "chart.js": "^2.8.0",. Chart is displaying as expected but only problem is that I am not able to increase the line width with borderWidth property.
Code:
import { SingleDataSet, Label, Color } from "ng2-charts";
import { ChartType, ChartOptions } from "chart.js";
public barChartType1: ChartType = "line";
public lineChartOptions: ChartOptions = {
responsive: true,
legend: { display: false },
scales: {
yAxes: [
{
display: false,
ticks: {
beginAtZero: false
},
scaleLabel: {
display: true,
labelString: '',
fontSize: 20,
}
},
]
},
elements: {
point:{
radius: 0,
borderWidth: 50
}
},
};
public lineChartColors: Color[] = [
{
borderColor: '#5081bd',
backgroundColor: 'transparent',
},
];
Template:
<canvas baseChart height="30vh" width="80vw"
[colors]="lineChartColors"
[datasets]="barChartDataSets1[customdata.index]"
[labels]="barChartLabels1[customdata.index]"
[options]="lineChartOptions"
[chartType]="barChartType1"
(chartHover)="chartHovered($event)"
(chartClick)="chartClicked($event)">
</canvas>
Inputs:
barChartDataSets1 [{"data":["2.00","2.00","2.00","2.00","2.00","2.00","2.00","2.00"]
barChartLabels1 [" "," "," ","ans1"," "," "," ","ans2"]
Output:
Is there any solution for this and why changing borderWidth property isn't working on it?
This is because you placed the option in the wrong namespace instead of using options.elements.point you need to place it in options.elements.line:
elements: {
point: {
radius: 0,
},
line: {
borderWidth: 8
}
},

chart js 2 how to set bar width

I'm using Chart js version: 2.1.4 and I'm not able to limit the bar width. I found two options on stackoverflow
barPercentage: 0.5
or
categorySpacing: 0
but neither of one works with the mentioned version. Is there a way to solve this issue without manually modifying the chart.js core library?
thanks
You were right : The attribute you have to edit is barPercentage.
But maybe the error comes from where you edited the value.
As you can see in the bar chart options :
Name : barPercentage
- Type : Number
- Default : 0.9
- Description : Percent (0-1) of the available width each bar should be within the category percentage. 1.0 will take the whole category width and put the bars right next to each other. Read More
The attribute is actually stored in scales.xAxes ("Options for xAxes" table).
So you just have to edit your chart this way :
var options = {
scales: {
xAxes: [{
barPercentage: 0.4
}]
}
}
Here is a fully working example with a custom width (0.2) for the bar :
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
data: [65, 59, 75, 81, 56, 55, 40],
}]
};
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: data,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
// Change here
barPercentage: 0.2
}]
}
}
});
console.log(myChart);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.js"></script>
<canvas id="myChart"></canvas>
Update (Chart.js Version 2.2.0+)
As stated in the Release Version 2.2.0 - Candidate 2 :
Enhancements
Can now manually configure the thickness of a bar in a bar chart. Use a new barThickness option on the correct axis to set the thickness of a bar.
And so on ...
For version 2.8+ (and apparently as far back as 2.2), there are now some excellent controls over the bar thickness, max thickness, etc.
Per the Chart.js documentation, you would set them like so:
{
type: 'bar', // or 'horizontalBar'
data: ...,
options: {
scales: {
xAxes: [{
barThickness: 6, // number (pixels) or 'flex'
maxBarThickness: 8 // number (pixels)
}]
}
}
}
As of v2.7.2 it can be done by:
scales: {
xAxes: [{
maxBarThickness: 100,
}],
}
In case if you are using ng2-chart in an angular project then the bar chart configuration looks Alike this:
npm install ng2-charts chart.js --save
import 'ng2-charts' in your module.
import { ChartsModule } from 'ng2-charts';
Now the bar chart configurations:
barChartOptions: ChartOptions = {
responsive: true,
maintainAspectRatio: false,
legend: {
display: false
},
};
barChartLabels: Label[] = ['2006', '2007', '2008', '2009', '2010', '2011', '2012'];
barChartType: ChartType = 'bar';
barChartLegend = true;
barChartPlugins = [];
barChartData: ChartDataSets[] = [
{
barThickness: 16,
barPercentage: 0.5,
data: [65, 59, 80],
label: 'Growth'
},
{
barThickness: 16,
barPercentage: 0.5,
data: [28, 48, 40],
label: 'Net'
}
];
barChartColors: Color[] = [
{ backgroundColor: '#24d2b5' },
{ backgroundColor: '#20aee3' },
];
Now the HTML part:
<div class="bar-chart-wrapper">
<canvas baseChart [datasets]="barChartData" [colors]="barChartColors"
[labels]="barChartLabels"
[options]="barChartOptions" [plugins]="barChartPlugins" [legend]="barChartLegend"
[chartType]="barChartType">
</canvas>
</div>
You can control the height of your chart container
.bar-chart-wrapper {
height: 310px;
}
barThickness and maxBarThickness (previously in ChartOptions[]) are now a part of ChartDataSets[].
As per above answer
Here is complete Bar chart graph using react chartjs2.
import React from 'react';
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
} from 'chart.js';
import { Bar } from 'react-chartjs-2';
ChartJS.register(
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
);
export const options = {
responsive: true,
plugins: {
legend: {
position: 'top', // lable position left/right/top/bottom
labels: {
boxWidth: 0, // lable box size
}
},
},
elements: {
point: {
radius: 1
}
},
scales: {
x: {
display: false, // show/ hide x-axis
grid: {
display: false // show/hide grid line in x-axis
},
},
y: {
display: false, // same as x-axis
grid: {
display: false
}
}
}
};
const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July'];
export const data = {
labels,
datasets: [
{
label: 'datasets', // label text
data: [100, 300, 500, 700],
backgroundColor: '#7b62ff', // bar / column color
barThickness: 6, // <<<<<<<<<<<< bar / column size
},
],
};
export default function ResumesGraph() {
return (
<div>
<Bar
data={data}
options={options}
width={'500px'}
height={'180px'}
/>
</div>
);
}
Try this
import {Chart} from "chart.js"
Chart.defaults.datasets.bar.maxBarThickness = 73;
//also try barPercentage
For those who are interested, i made a quick fork based on 3.9 branch to manage dynamic width :
https://github.com/stephanebouget/Chart.js/tree/3.9
For example :
Live demo
https://codepen.io/stephanebouget/pen/PoerxPP
var data = {
datasets: [{
label: 'Dataset #1',
backgroundColor: 'rgba(255,99,132,0.2)',
borderColor: 'rgba(255,99,132,1)',
borderWidth: 1,
hoverBackgroundColor: 'rgba(255,99,132,0.4)',
hoverBorderColor: 'rgba(255,99,132,1)',
data: [65, 59, 20, 81, 56, 55, 40],
setPercentage: [10, 2, 20, 40, 4, 6, 18], // Here is the magic !!!
}],
};

Categories