I am trying to display float bar on a browser.
But the item of float bar can not be found.
Is there no way to display it in Chart.js?
This page I found on GitHub was modifying Chart.js.
https://github.com/chartjs/Chart.js/pull/5262
http://pravopys.net/chartjs/samples/charts/bar/horizontal.html
However, I did not understand how to modify it.
Also, this page seemed to be trying to implement float bar support. However, it does not seem to be implemented yet.
https://github.com/chartjs/Chart.js/pull/6056
I will put the code of the page of float bar introduced above.
However, even if this code was used, only the lower part was displayed.
I think that it is also necessary to modify Chart.js itself.
window.chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
window.randomScalingFactor = function() {
// return Math.round(Samples.utils.rand(-100, 100));
return (Math.random()*200 - 100);
};
if (document.location.hostname.match(/^(www\.)?chartjs\.org$/)) {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-28909194-3', 'auto');
ga('send', 'pageview');
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
var MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var color = Chart.helpers.color;
var horizontalBarChartData = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [{
label: 'Dataset 1',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
borderWidth: 1,
data: [
[20, 70],
[-20,-70],
[getRandomInt(10,50), getRandomInt(50,100)],
[getRandomInt(10,50), getRandomInt(50,100)],
[getRandomInt(10,50), getRandomInt(50,100)],
[getRandomInt(10,50), getRandomInt(50,100)],
randomScalingFactor(),
randomScalingFactor()
]
}, {
label: 'Dataset 2',
backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
borderColor: window.chartColors.blue,
data: [
[-10, 30],
[-20,-70],
[getRandomInt(-10,-50), getRandomInt(-50,-100)],
[getRandomInt(-10,-50), getRandomInt(-50,-100)],
[getRandomInt(-10,-50), getRandomInt(-50,-100)],
[getRandomInt(-10,-50), getRandomInt(-50,-100)],
randomScalingFactor(),
randomScalingFactor()
]
}]
};
console.log(horizontalBarChartData);
window.onload = function() {
console.log('t');
console.log(horizontalBarChartData);
let ctx = document.getElementById("Chart").getContext('2d');
window.myHorizontalBar = new Chart(ctx, {
type: 'horizontalBar',
data: horizontalBarChartData,
options: {
// Elements options apply to all of the options unless overridden in a dataset
// In this case, we are setting the border of each horizontal bar to be 2px wide
elements: {
rectangle: {
borderWidth: 2,
}
},
responsive: true,
legend: {
position: 'right',
},
title: {
display: true,
text: 'Chart.js Horizontal Bar Chart'
}
}
});
};
document.getElementById('randomizeData').addEventListener('click', function() {
var zero = Math.random() < 0.2 ? true : false;
horizontalBarChartData.datasets.forEach(function(dataset) {
dataset.data = dataset.data.map(function() {
return zero ? 0.0 : randomScalingFactor();
});
});
window.myHorizontalBar.update();
});
var colorNames = Object.keys(window.chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[horizontalBarChartData.datasets.length % colorNames.length];
var dsColor = window.chartColors[colorName];
var newDataset = {
label: 'Dataset ' + horizontalBarChartData.datasets.length,
backgroundColor: color(dsColor).alpha(0.5).rgbString(),
borderColor: dsColor,
data: []
};
for (var index = 0; index < horizontalBarChartData.labels.length; ++index) {
newDataset.data.push(randomScalingFactor());
}
horizontalBarChartData.datasets.push(newDataset);
window.myHorizontalBar.update();
});
document.getElementById('addData').addEventListener('click', function() {
if (horizontalBarChartData.datasets.length > 0) {
var month = MONTHS[horizontalBarChartData.labels.length % MONTHS.length];
horizontalBarChartData.labels.push(month);
for (var index = 0; index < horizontalBarChartData.datasets.length; ++index) {
horizontalBarChartData.datasets[index].data.push(randomScalingFactor());
}
window.myHorizontalBar.update();
}
});
document.getElementById('removeDataset').addEventListener('click', function() {
horizontalBarChartData.datasets.splice(0, 1);
window.myHorizontalBar.update();
});
document.getElementById('removeData').addEventListener('click', function() {
horizontalBarChartData.labels.splice(-1, 1); // remove the label first
horizontalBarChartData.datasets.forEach(function(dataset) {
dataset.data.pop();
});
window.myHorizontalBar.update();
});
I asked for a float bar. However, in fact, only a bar chart was displayed.
If you can not do it in Chart.js, I would appreciate it if you could show other possible libraries.
Floating bars are officially available since Chart.js v2.9.0. The feature was merged into chartjs:master with pull request #6056. Individual bars can now be specified with the syntax [min, max].
<html>
<head>
<title>Floating Bars</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<div>
<canvas id="canvas" height="100"></canvas>
</div>
<script>
window.onload = function() {
var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: [1, 2, 3, 4, 5],
datasets: [{
label: 'data',
data: [[-3, 5], [2, 10], [1, 3], [-4, -1], [4, 8]],
backgroundColor: 'lightblue'
}]
},
options: {
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Horizontal Floating Bars'
}
}
});
};
</script>
</body>
</html>
Related
Circling back around to this and I thought I had this worked out but apparently I do not. I am somewhat new to charts. I want the graph to show a line from zero even if there is no data for that month. This is a bit lengthy and I apologize for all of the code, but without it you will not understand what it is doing.
Here is my Controller Json:
var type3 = "Equipment";
var types3 = acct.TransactionType.Where(a => a.Type == type3).FirstOrDefault();
var q2 = from t in acct.Transaction.Where(t => t.Type == types3.TypeId && t.TransactionDate.Year.ToString() == currentYear)
group t by new
{
t.TransactionDate.Year,
t.TransactionDate.Month,
type = t.Type
} into g
select new
{
Total2 = g.Sum(t => t.CreditAmount) ?? 0
};
I have this same code for 2 other items I am showing. They show a graph from Zero. This is because in January at some point there is data. So It starts at 0. This particular area does not have any data in January and only has data in one month. So it doesn't even show a Dot for that month. In between 2 months if there is no data it will dip to zero.
I fixed that issue with adding ?? 0 above.
It appears to only have an effect if there is data before and after the time. So I am wondering if there is a way to show a line all the way across from zero to the point where there is data and then dip back down to zero after with plot dots.
Here is my java script code for the CHTML Page.
function SalesByMonth() {
$.ajax({
url: '#Url.Action("GetChartData", "Dashboard", new { Year = "year" })'.replace('year', currentYear),
data: JSON,
contentType: "application/json; charset=utf-8",
method: "get",
dataType: "json",
error: function (_, err) {
console.log(_, err)
},
success: function (response) {
console.log(response);
var jsonresult = response
//var labels = jsonresult.result.map(function (e) {
// return e.Months;
//});
var data = jsonresult.result1.map(function (e) {
return e.Total;
});
var data2 = jsonresult.result2.map(function (e) {
return e.Total2;
});
var data3 = jsonresult.result3.map(function (e) {
return e.Total3;
});
var ctx = document.getElementById("monthlySalesChart").getContext("2d");
var cpieChart = new Chart(ctx, {
type: 'line',
data: {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets: [{
label: 'Parts Sales',
backgroundColor: 'rgb(204, 102, 0)',
borderColor: 'rgb(204, 102, 0)',
fill: false,
//strokeColor: 'rgb(210, 214, 222)',
//pointColor: 'rgb(210, 214, 222)',
//pointStrokeColor: '#c1c7d1',
//pointHighlightFill: '#fff',
//pointHighlightStroke: 'rgb(220,220,220)',
data: data,
borderWidth: 1
},
{
label: 'Service Sales',
backgroundColor: 'rgb(210, 214, 250)',
borderColor: 'rgb(210, 214, 250)',
fill: false,
//strokeColor: 'rgb(210, 214, 222)',
//pointColor: 'rgb(210, 214, 222)',
//pointStrokeColor: '#c1c7d1',
//pointHighlightFill: '#fff',
//pointHighlightStroke: 'rgb(220,220,220)',
data: data2,
borderWidth: 1
},
{
label: 'Machine Sales',
backgroundColor: 'rgb(0,102,204)',
borderColor: 'rgb(0,102,204)',
fill: false,
//strokeColor: 'rgba(60,141,188,0.8)',
//pointColor: '#3b8bba',
//pointStrokeColor: 'rgba(60,141,188,1)',
//pointHighlightFill: '#fff',
//pointHighlightStroke: 'rgba(60,141,188,1)',
data: data3,
borderWidth: 1
}],
},
options: {
scales: {
xAxes: [{
gridLines: {
display: false
}
}],
yAxes: [{
//gridLines: {
// display: false
//},
ticks: {
beginAtZero: true,
//min: 200,
max: 80000,
stepSize: 2000,
callback: function (value, index, values) {
value = value.toString();
value = value.split(/(?=(?:...)*$)/);
value = value.join(',');
return '$' + value + '.00';
}
}
}]
}
}
});
}
});
};
If you need anything else let me know.
Thanks for your help!
UPDATE: If it helps I am using Chart.js v2.9.3
UPDATE: Found 1 Error.
Where it has Total2 = g.sum(t => t.CreditAmount) ?? 0 Should be Total3 = g.sum(t => t.CreditAmount) ?? 0. I already had a Total2 in a prev code block. However I am now getting a Tick but it is showing up on January and not May like it should. Date in the database is correct. So I am not sure why it is coming up in January.
UPDATE: The Only thing that I can figure out is that since there is only 1 entry in the database under that type, It doesn't have anything else to compare it too in the same month. It only returns 1 record for that. So I need to find out how to check the date and simply have a zero for that month show up regardless of the amount of records.
I need to make a chart at the level with a row in the table, are there any tips on how to implement this enter image description here
I need the chart lines to match the row level in the table
and this code draws a separate chart
const diag = () => {
document.getElementById("canvasic").innerHTML = ' ';
document.getElementById("canvasic").innerHTML = '<canvas id="densityChart" className="canav"></canvas>';
densityCanvas = document.getElementById("densityChart");
//remove canvas from container
Chart.defaults.global.defaultFontFamily = "Arial";
Chart.defaults.global.defaultFontSize = 16;
var densityData = {
label: 'CallVol',
data:calloiList1,
backgroundColor: 'rgba(0,128,0, 0.6)',
borderColor: 'rgba(0,128,0, 1)',
borderWidth: 2,
hoverBorderWidth: 0
};
var densityData1 = {
label: 'PutVol',
data:calloiList3 ,
backgroundColor: 'rgba(255,0,0, 0.6)',
borderColor: 'rgba(255,0,0, 1)',
borderWidth: 2,
hoverBorderWidth: 0
};
var chartOptions = {
scales: {
yAxes: [{
barPercentage: 0.5
}]
},
elements: {
rectangle: {
borderSkipped: 'left',
}
}
};
var barChart = new Chart(densityCanvas, {
type: 'horizontalBar',
data: {
labels: calloiList4,
datasets: [densityData,densityData1],
},
options: chartOptions
}
);
}
enter image description here
I wanted to stream live data in the form of a chart. I'm new to Javascript, so I wanted to first experiment with the sample on this page.
https://web.archive.org/web/20211113012042/https://nagix.github.io/chartjs-plugin-streaming/latest/samples/charts/line-horizontal.html
The code is given as:
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
function randomScalingFactor() {
return (Math.random() > 0.5 ? 1.0 : -1.0) * Math.round(Math.random() * 100);
}
function onRefresh(chart) {
chart.config.data.datasets.forEach(function(dataset) {
dataset.data.push({
x: Date.now(),
y: randomScalingFactor()
});
});
}
var color = Chart.helpers.color;
var config = {
type: 'line',
data: {
datasets: [{
label: 'Dataset 1 (linear interpolation)',
backgroundColor: color(chartColors.red).alpha(0.5).rgbString(),
borderColor: chartColors.red,
fill: false,
lineTension: 0,
borderDash: [8, 4],
data: []
}, {
label: 'Dataset 2 (cubic interpolation)',
backgroundColor: color(chartColors.blue).alpha(0.5).rgbString(),
borderColor: chartColors.blue,
fill: false,
cubicInterpolationMode: 'monotone',
data: []
}]
},
options: {
title: {
display: true,
text: 'Line chart (hotizontal scroll) sample'
},
scales: {
xAxes: [{
type: 'realtime'
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'value'
}
}]
},
tooltips: {
mode: 'nearest',
intersect: false
},
hover: {
mode: 'nearest',
intersect: false
},
plugins: {
streaming: {
duration: 20000,
refresh: 1000,
delay: 2000,
onRefresh: onRefresh
}
}
}
};
window.onload = function() {
var ctx = document.getElementById('myChart').getContext('2d');
window.myChart = new Chart(ctx, config);
};
document.getElementById('randomizeData').addEventListener('click', function() {
config.data.datasets.forEach(function(dataset) {
dataset.data.forEach(function(dataObj) {
dataObj.y = randomScalingFactor();
});
});
window.myChart.update();
});
var colorNames = Object.keys(chartColors);
document.getElementById('addDataset').addEventListener('click', function() {
var colorName = colorNames[config.data.datasets.length % colorNames.length];
var newColor = chartColors[colorName];
var newDataset = {
label: 'Dataset ' + (config.data.datasets.length + 1),
backgroundColor: color(newColor).alpha(0.5).rgbString(),
borderColor: newColor,
fill: false,
lineTension: 0,
data: []
};
config.data.datasets.push(newDataset);
window.myChart.update();
});
document.getElementById('removeDataset').addEventListener('click', function() {
config.data.datasets.pop();
window.myChart.update();
});
document.getElementById('addData').addEventListener('click', function() {
onRefresh(window.myChart);
window.myChart.update();
});
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<script src="https://github.com/nagix/chartjs-plugin-streaming/releases/download/v1.5.0/chartjs-plugin-streaming.min.js"></script>
</head>
<body>
<div>
<canvas id="myChart"></canvas>
</div>
<p>
<button id="randomizeData">Randomize Data</button>
<button id="addDataset">Add Dataset</button>
<button id="removeDataset">Remove Dataset</button>
<button id="addData">Add Data</button>
</p>
</body>
When I copy and paste it into jsfiddle, the first code snippet going into the Javascript section and the second going into the HTML section. However, nothing happens? Could someone explain why/help me edit it so that it works?
Note: the code above is not my own, it belongs to this guy
In JSFiddle, the load type is set to 'On Load' by default, so you cannot handle the load event. Setting the load type to 'No wrap - bottom of ' works (in the pop-up menu in the Javascript section).
I have a problem with Chart.js.
I want an an alert show me the ID value set in the dataset when I click on a point in the chart.
I have tried using getElementsAtEvent(evt);, but it doesn't work as I expected.
Can somebody help me? Thanks!
var ctx = document.getElementById("myChart");
var color = ["#ff6384", "#5959e6", "#2babab", "#8c4d15", "#8bc34a", "#607d8b", "#009688"];
var scatterChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: 'Linea A',
backgroundColor: "transparent",
borderColor: color[1],
pointBackgroundColor: color[1],
pointBorderColor: color[1],
pointHoverBackgroundColor: color[1],
pointHoverBorderColor: color[1],
data: [{
x: "2014-09-02",
y: 90,
id: '1A'
}, {
x: "2014-11-02",
y: 96,
id: '2A'
}, {
x: "2014-12-03",
y: 97,
id: '3A'
}]
},
{
label: 'Linea B',
backgroundColor: "transparent",
borderColor: color[2],
pointBackgroundColor: color[2],
pointBorderColor: color[2],
pointHoverBackgroundColor: color[2],
pointHoverBorderColor: color[2],
data: [{
x: "2014-09-01",
y: 96,
id: "1B"
}, {
x: "2014-10-04",
y: 95.8,
id: "2B"
}, {
x: "2014-11-06",
y: 99,
id: "3B"
}]
}
]
},
options: {
title: {
display: true,
text: 'Polveri',
fontSize: 18
},
legend: {
display: true,
position: "bottom"
},
scales: {
xAxes: [{
type: 'time',
time: {
displayFormats: {
'millisecond': 'MM/YY',
'second': 'MM/YY',
'minute': 'MM/YY',
'hour': 'MM/YY',
'day': 'MM/YY',
'week': 'MM/YY',
'month': 'MM/YY',
'quarter': 'MM/YY',
'year': 'MM/YY',
},
tooltipFormat: "DD/MM/YY"
}
}]
}
}
});
document.getElementById("myChart").onclick = function(evt) {
var activePoints = scatterChart.getElementsAtEvent(evt);
var firstPoint = activePoints[1];
console.log(firstPoint._datasetIndex);
console.log(firstPoint._index);
var label = scatterChart.data.labels[firstPoint._index];
console.log(scatterChart.data.datasets[0].data[0].id);
var value = scatterChart.data.datasets[firstPoint._datasetIndex].data[firstPoint._index];
if (firstPoint !== undefined)
alert(label + ": " + value);
};
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.js">
</script>
<canvas id="myChart" width="400" height="100"></canvas>
You have to change your label variable assignment from,
var label = scatterChart.data.labels[firstPoint._index];
To,
var label = scatterChart.data.datasets[firstPoint._index].label;
And you may also need to change your alert statment as,
alert(label + ": " + value.x);
Here is the working DEMO: https://jsfiddle.net/dt6c9jev/
Hope this helps!.
You need to use the .getElementAtEvent() prototype method instead of .getElementsAtEvent(). The difference being the first only returns the single point that you clicked whereas the other returns all points at the X axis for that click.
Here is an example.
document.getElementById("canvas").onclick = function(evt) {
var activePoint = myLine.getElementAtEvent(event);
// make sure click was on an actual point
if (activePoint.length > 0) {
var clickedDatasetIndex = activePoint[0]._datasetIndex;
var clickedElementindex = activePoint[0]._index;
var label = myLine.data.labels[clickedElementindex];
var value = myLine.data.datasets[clickedDatasetIndex].data[clickedElementindex];
alert("Clicked: " + label + " - " + value);
}
};
You can see a demonstration at this codepen.
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 !!!
}],
};