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

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

Related

make horizontal graph with percentage :react js

I trying to make a horizontal chart with react-chartjs i want each data to show the percentage
import React, { Component } from "react";
import { HorizontalBar } from "react-chartjs-2";
export default class Button extends Component {
render() {
const dataHorBar = {
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, 40]
}
]
};
return (
<div>
<HorizontalBar data={dataHorBar} />
</div>
);
}
}
Here is the code of what I have tried
https://codesandbox.io/s/react-chartjs-bar-horizontal-bar-forked-be9wil
I also want to remove the background lines and make the graph more rounded edge
In order to use the feature for having rounded rectangles, you need to update to the v3 of chartjs, therefore, the following code will be working only on this version. But you can adapt it to a previous version, you will just not be able to change the border radius of the rectangle.
You can use the datalabels plugin, in order to display custom text in your chart, and format the label like this:
options: {
plugins: {
datalabels: {
formatter: value => value + " %", // Add the percentage after the value
align: "end",
anchor: "end",
clip: true,
}
}
}
For the shapes, you can use the option borderRadius, to have rounded edges. You can find more information here, but in the end, you just have to specify a value for the borderRadius, in each dataset:
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, 40],
borderRadius: 50, // Give a number
}
]
Finally, for removing the grid lines, you can use this snippet, and pass those options to your chart
options: {
scales: {
x: {
grid: {
display: false // Hide x grid
}
},
y: {
grid: {
display: false // Hide y grid
}
}
}
};
That's it for the ground principle. Here is a live working example, if you really wants to see how to implement it.

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

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

react-chartjs-2 chart.js: How to make strokewidth of dougnut chart thin?

I am implementing one doughnut chart in react js by using react-chart.js-2 chart.js, but I want to customize it according to my requirements, I have done already some customization, but one I need to do is, to make the width of chart thin.
Current Image
enter image description here
Required Image
enter image description here
import React from "react";
import { Doughnut } from "react-chartjs-2";
const data = {
datasets: [
{
data: [8, 25, 2, 4, 3, 21, 2],
backgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56",
"black",
"blue",
"red",
"purple",
],
borderColor: "transparent",
},
],
};
function App() {
return (
<div className="App">
{" "}
<h2>Doughnut Example</h2>
<Doughnut
data={data}
options={{
responsive: true,
maintainAspectRatio: false,
tooltips: false,
height: "2",
}}
/>
</div>
);
}
export default App;
Edit cutout property in options
let options = {
responsive: true,
cutout:"80%",
legend: {
display: false,
},
layout: {
padding: 10,
},
};
You need to define the cutoutPercentage option inside the chart options as follows:
<Doughnut
data={data}
options={{
responsive: true,
cutoutPercentage: 80,
...
}}
/>
cutoutPercentage: The percentage of the chart that is cut out of the middle (default value is 50).

How can I change the font (family) for the labels in Chart.JS?

I want to change the font to something snazzier in my Chart.JS horizontal bar chart. I've tried the following, but none of it works:
var optionsBar = {
. . .
//fontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
//bodyFontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
//bodyFontFamily: "'Candara'"
label: {
font: {
family: "Georgia"
}
}
};
I also read that this would work:
Chart.defaults.global.defaultFont = "Georgia"
...but where would this code go, and how exactly should it look? I tried this:
priceBarChart.defaults.global.defaultFont = "Georgia";
...but also to no good effet.
For the full picture/context, here is all the code that makes up this chart:
HTML
<div class="chart">
<canvas id="top10ItemsChart" class="pie"></canvas>
<div id="pie_legend"></div>
</div>
JQUERY
var ctxBarChart =
$("#priceComplianceBarChart").get(0).getContext("2d");
var barChartData = {
labels: ["Bix Produce", "Capitol City", "Charlies Portland",
"Costa Fruit and Produce", "Get Fresh Sales",
"Loffredo East", "Loffredo West", "Paragon", "Piazza Produce"],
datasets: [
{
label: "Price Compliant",
backgroundColor: "rgba(34,139,34,0.5)",
hoverBackgroundColor: "rgba(34,139,34,1)",
data: [17724, 5565, 3806, 5925, 5721, 6635, 14080, 9027,
25553]
},
{
label: "Non-Compliant",
backgroundColor: "rgba(255, 0, 0, 0.5)",
hoverBackgroundColor: "rgba(255, 0, 0, 1)",
data: [170, 10, 180, 140, 30, 10, 50, 100, 10]
}
]
}
var optionsBar = {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
},
//fontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
//bodyFontFamily: "'Candara', 'Calibri', 'Courier', 'serif'"
//bodyFontFamily: "'Candara'"
//Chart.defaults.global.defaultFont = where does this go?
label: {
font: {
family: "Georgia"
}
}
};
var priceBarChart = new Chart(ctxBarChart, {
type: 'horizontalBar',
data: barChartData,
options: optionsBar
});
//priceBarChart.defaults.global.defaultFont = "Georgia";
I even tried this:
CSS
.candaraFont13 {
font-family:"Candara, Georgia, serif";
font-size: 13px;
}
HTML
<div class="graph_container candaraFont13">
<canvas id="priceComplianceBarChart"></canvas>
</div>
...but I reckon the canvas drawing takes care of the font appearance, as adding this made no difference.
UPDATE
I tried this and it completely broke it:
Chart.defaults.global = {
defaultFontFamily: "Georgia"
}
UPDATE 2
As Matthew intimated, this worked (before any of the chart-specific script):
Chart.defaults.global.defaultFontFamily = "Georgia";
This should be useful: http://www.chartjs.org/docs/. It says "There are 4 special global settings that can change all of the fonts on the chart. These options are in Chart.defaults.global".
You'll need to change defaultFontFamily for the font. And defaultFontColor, defaultFontSize, and defaultFontStyle for color, size, etc.
If you wanted to add the font-family to the chart object then you can add it in the options object.
options: {
legend: {
labels: {
fontFamily: 'YourFont'
}
}...}
Here is a link to the docs: https://www.chartjs.org/docs/latest/general/fonts.html
Change font size, color, family and weight using chart.js
scales: {
yAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}],
xAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}]
}
See the full code
<!doctype html>
<html>
<head>
<title>Chart.js</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet">
<script src="js/Chart.bundle.js"></script>
<script src="js/utils.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
font-weight:700;
}
</style>
</head>
<body>
<div id="container" style="width:70%;">
<canvas id="canvas"></canvas>
</div>
<script>
var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var color = Chart.helpers.color;
var barChartData = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
datasets: [{
label: 'Completed',
// Green
backgroundColor: '#4caf50',
borderColor: '#4caf50',
borderWidth: 1,
data: [
5, 15, 25, 35, 45, 55
]
}, {
label: 'Created',
// Blue
backgroundColor: '#1976d2',
borderColor: '#1976d2',
borderWidth: 1,
data: [
10, 20, 30, 40, 50, 60
]
}]
};
window.onload = function () {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
responsive: true,
legend: {
position: 'top',
onClick: null
},
title: {
display: true,
text: '',
fontSize: 20
},
scales: {
yAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}],
xAxes: [{ticks: {fontSize: 12, fontFamily: "'Roboto', sans-serif", fontColor: '#000', fontStyle: '500'}}]
}
}
});
};
</script>
</body>
</html>
You named the chart priceBarChart in the following part of your code:
var priceBarChart = new Chart(ctxBarChart, {
type: 'horizontalBar',
data: barChartData,
options: optionsBar
})
Which means that priceBarChart.defaults.global.defaultFont = 'Georgia' will 'dive' into the variable priceBarChart, go into its default properties, change one of its global properties and that one is defaultFont, exactly what you want.
But when you apply this code, you basically create the chart with the wrong font and then change it again, which is a bit ugly. What you need to do is tell the chart what the font is beforehand.
You do this by merging your font declaration with the rest of the options, just like how you did it with your variables barChartData and optionsBar.
After you've created barChartData and optionsBar, create another variable with the name, let's say, defaultOptions, like so:
var defaultOptions = {
global: {
defaultFont: 'Georgia'
}
}
You can see that it has the same structure. You go into the global options, and change its defaultFont property. Now you need to apply it to the created chart at the moment it is created, like so:
var priceBarChart = new Chart(ctxBarChart, {
type: 'horizontalBar',
data: barChartData,
options: optionsBar,
defaults: defaultOptions //This part has been added
})
This method of overwriting options is what is being used in almost every JavaScript plugin. When you create a new instance, the plugin copies an object that contains objects that contain objects and so forth. But these objects can be modified with additional options, like barChartData, optionsBar and defaultOptions.
I hope this helps!

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