Export HTML content with Chart.jscanvases to PDF - javascript

I have an HTML page with around 10 charts generated by chart.js (so these are canvas elements). I want to be able to export the page content into a PDF file.
I've tried using jsPDF's .fromHTML function, but it doesn't seem to support exporting the canvas contents. (Either that or I'm doing it wrong). I just did something like:
$(".test").click(function() {
var doc = new jsPDF()
doc.fromHTML(document.getElementById("testExport"));
doc.save('a4.pdf')
});
Any alternative approaches would be appreciated.

You should use html2canvas (to support canvas export and get a better representation of html elements), along with jsPDF.
Here is an example :
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May'],
datasets: [{
label: 'DST',
data: [3, 1, 4, 2, 5],
backgroundColor: 'rgba(0, 119, 290, 0.2)',
borderColor: 'rgba(0, 119, 290, 0.6)',
fill: false
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
stepSize: 1
}
}]
}
}
});
function saveAsPDF() {
html2canvas(document.getElementById("chart-container"), {
onrendered: function(canvas) {
var img = canvas.toDataURL(); //image data of canvas
var doc = new jsPDF();
doc.addImage(img, 10, 10);
doc.save('test.pdf');
}
});
}
#chart-container {
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<div id="chart-container">
ChartJS - Line Chart
<canvas id="ctx"></canvas>
</div><br>
<button onclick="saveAsPDF();">save as pdf</button>

Related

How to put images on Y axis of line chart in Chart.js? [duplicate]

I am generating a chart.js canvas bar chart. What I am trying to do is, inside of the labels array, add images that go with each label, as opposed to just the text label itself. Here is the code for the chart: The json object that I am getting data from has an image url that I want to use to display the picture:
$.ajax({
method: "get",
url: "http://localhost:3000/admin/stats/show",
dataType: "json",
error: function() {
console.log("Sorry, something went wrong");
},
success: function(response) {
console.log(response)
var objectToUse = response.top_dogs
var updateLabels = [];
var updateData = [];
for (var i = 0; i < objectToUse.length; i+=1) {
updateData.push(objectToUse[i].win_percentage * 100);
updateLabels.push(objectToUse[i].title);
}
var data = {
labels: updateLabels,
datasets: [
{
label: "Top Winners Overall",
fillColor: get_random_color(),
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: get_random_color(),
highlightStroke: "rgba(220,220,220,1)",
data: updateData
}
]
};
var options = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines: true,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 2,
};
var loadNewChart = new Chart(barChart).Bar(data, options);
}
});
If anyone has a solution it would be greatly appreciated!
I'm aware that this is an old post but since it has been viewed so many times, I'll describe a solution that works with the current Chart.js version 2.9.3.
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the afterDraw hook to draw images (icons) directly on the canvas using CanvasRenderingContext2D.
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
xAxis.ticks.forEach((value, index) => {
var x = xAxis.getPixelForTick(index);
ctx.drawImage(images[index], x - 12, yAxis.bottom + 10);
});
}
}],
The position of the labels will have to be defined through the xAxes.ticks.padding as follows:
xAxes: [{
ticks: {
padding: 30
}
}],
Please have a look at the following runnable code snippet.
const labels = ['Red Vans', 'Blue Vans', 'Green Vans', 'Gray Vans'];
const images = ['https://i.stack.imgur.com/2RAv2.png', 'https://i.stack.imgur.com/Tq5DA.png', 'https://i.stack.imgur.com/3KRtW.png', 'https://i.stack.imgur.com/iLyVi.png']
.map(png => {
const image = new Image();
image.src = png;
return image;
});
const values = [48, 56, 33, 44];
new Chart(document.getElementById("myChart"), {
type: "bar",
plugins: [{
afterDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['y-axis-0'];
xAxis.ticks.forEach((value, index) => {
var x = xAxis.getPixelForTick(index);
ctx.drawImage(images[index], x - 12, yAxis.bottom + 10);
});
}
}],
data: {
labels: labels,
datasets: [{
label: 'My Dataset',
data: values,
backgroundColor: ['red', 'blue', 'green', 'lightgray']
}]
},
options: {
responsive: true,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
padding: 30
}
}],
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="90"></canvas>
Chart.js v3+ solution to pie, doughnut and polar charts
With version 3 of Chart.js and the updated version of chart.js-plugin-labels, this is now incredbly simple.
in options.plugins.labels, add render: image and the nested array images with objects containing the properties src, width and height.
const data = {
labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4', 'Label 5', 'Label 6', 'Label 7', 'Label 8'],
datasets: [{
label: 'Image labels',
// Making each element take up full width, equally divided
data: [100, 100, 100, 100, 100, 100, 100, 100],
backgroundColor: [
'rgba(255, 26, 104, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)',
'rgba(0, 0, 0, 0.2)',
'rgba(20, 43, 152, 0.2)'
]
}]
};
const config = {
type: 'doughnut',
data,
options: {
plugins: {
// Accessing labels and making them images
labels: {
render: 'image',
images: [{
src: 'https://cdn0.iconfinder.com/data/icons/google-material-design-3-0/48/ic_book_48px-256.png',
height: 25,
width: 25
},
{
src: 'https://cdn3.iconfinder.com/data/icons/glypho-free/64/pen-checkbox-256.png',
height: 25,
width: 25
},
{
src: 'https://cdn1.iconfinder.com/data/icons/jumpicon-basic-ui-glyph-1/32/-_Home-House--256.png',
height: 25,
width: 25
},
{
src: 'https://cdn1.iconfinder.com/data/icons/social-media-vol-3/24/_google_chrome-256.png',
height: 25,
width: 25
},
{
src: 'https://cdn0.iconfinder.com/data/icons/google-material-design-3-0/48/ic_book_48px-256.png',
height: 25,
width: 25
},
{
src: 'https://cdn3.iconfinder.com/data/icons/glypho-free/64/pen-checkbox-256.png',
height: 25,
width: 25
},
{
src: 'https://cdn1.iconfinder.com/data/icons/jumpicon-basic-ui-glyph-1/32/-_Home-House--256.png',
height: 25,
width: 25
},
{
src: 'https://cdn1.iconfinder.com/data/icons/social-media-vol-3/24/_google_chrome-256.png',
height: 25,
width: 25
},
]
}
}
}
};
// render init block
const myChart = new Chart(
document.getElementById('myChart').getContext('2d'),
config
);
.chartCard {
width: 100vw;
height: 500px;
display: flex;
align-items: center;
justify-content: center;
}
.chartBox {
width: 600px;
padding: 20px;
}
<div class="chartCard">
<div class="chartBox">
<canvas id="myChart"></canvas>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://unpkg.com/chart.js-plugin-labels-dv#3.0.5/dist/chartjs-plugin-labels.min.js"></script>

How to get radar chart coordinates using getValueForDistanceFromCenter with Chart.js?

I am experimenting with Chart.js to build radar charts. I mastered the basics (see basic chart below), but I would like to use the x y coordinates of the graph to place texts directly on the canvas.
After some digging, I found out that it is not possible to use getValueForPixel or getPixelForTick in a radar chart. See this github issue. In the connecting thread, a new method getValueForDistanceFromCenter is introduced.
As I understand it, it would be possible to calculate the distance from the center with this method, and use it to get coordinates. I searched the Chart.js documentation and other sites, but cannot find any code examples or information on how to implement this.
Can somebody point me in the right direction how to implement the method in the code?
var data = {
labels: ["Ball Skills", "Shooting", "Physical"],
datasets: [{
label: [`ikke`, `jij`],
backgroundColor: "rgba(38,120,255,0.2)",
borderColor: "rgba(38,120,255, 1)",
data: [90, 90, 90]
}]
};
var options = {
responsive: true,
tooltips: false,
title: {
text: 'Basic example',
display: true,
position: `bottom`,
},
scale: {
angleLines: {
display: true
},
ticks: {
suggestedMin: 0,
suggestedMax: 100,
stepSize: 25,
maxTicksLimit: 11,
display: false,
}
},
legend: {
labels: {
padding: 10,
fontSize: 14,
lineHeight: 30,
},
},
};
var myChart = new Chart(document.getElementById("chart"), {
type: 'radar',
data: data,
options: options
});
The radialLinear scale (in version 2.9.4 that I have seen your are using version 2) there is the method getValueForDistanceFromCenter(value) to get the distance from center but there is another method getPointPositionForValue(index, value) which can provide you the point at a specif index of your data.
To use them and to draw what you want on chart using those points, you need to implement a plugin.
In the below snippet, I'm drawing a rect between the points at a specific value.
const ctx = document.getElementById("myChart");
const data = {
labels: ["Ball Skills", "Shooting", "Physical"],
datasets: [{
label: [`ikke`, `jij`],
backgroundColor: "rgba(38,120,255,0.2)",
borderColor: "rgba(38,120,255, 1)",
data: [50, 50, 50]
}]
};
const options = {
responsive: true,
tooltips: false,
title: {
text: 'Basic example',
display: true,
position: `bottom`,
},
scale: {
angleLines: {
display: true
},
ticks: {
suggestedMin: 0,
suggestedMax: 100,
stepSize: 25,
maxTicksLimit: 11,
display: false,
}
},
legend: {
labels: {
padding: 10,
fontSize: 14,
lineHeight: 30,
},
},
};
const plugin = {
id: 'getDistance',
afterDraw(chart) {
const c = chart.ctx;
const rScale = chart.scale;
c.save();
chart.data.datasets[0].data.forEach(function(item, index) {
const point = rScale.getPointPositionForValue(0.5 + index, 50);
c.beginPath();
c.fillStyle = 'red';
c.fillRect(point.x - 5, point.y - 5, 10, 10);
c.fill();
});
c.restore();
}
};
const myChart = new Chart(ctx, {
type: 'radar',
plugins: [plugin],
data: data,
options: options
});
.myChartDiv {
max-width: 600px;
max-height: 400px;
}
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4/dist/Chart.min.js"></script>
<html>
<body>
<div class="myChartDiv">
<canvas id="myChart" width="600" height="400"/>
</div>
</body>
</html>

RGraph with missing data points

I want to plot an area fill line chart with multiple series, using javascript & RGraph, for a period between two dates, but I do not have data points for every date; how do I do this with RGraph?
I cannot miss out dates in the data I pass to RGraph because although some of the series do not have that data, it might be that other series do (e.g. ABC has data for January and March, and XYZ has data for January and April).
I must have all dates for the year, which is represented with a horizontal axis showing just the month/period labels.
I have boiled this down to a simplified example below, and with a jsFiddle example on https://jsfiddle.net/Abeeee/25m1sc7d/1/
Both the code below and the JSFiddle show two charts controlled by the drawAll() function, which has a variable x in it. I want the second chart (cvs2) which uses x=null to not include plotting that null but simply draw the red line/area between 100 and 200, resulting a similar chart to the first one (cvs1).
<!DOCTYPE HTML>
<html>
<head>
<script src='https://www.rgraph.net/libraries/RGraph.common.core.js'></script>
<script src='https://www.rgraph.net/libraries/RGraph.common.dynamic.js'></script>
<script src='https://www.rgraph.net/libraries/RGraph.common.effects.js'></script>
<script src='https://www.rgraph.net/libraries/RGraph.common.key.js'></script>
<script src='https://www.rgraph.net/libraries/RGraph.common.tooltips.js'></script>
<script src='https://www.rgraph.net/libraries/RGraph.drawing.rect.js'></script>
<script src='https://www.rgraph.net/libraries/RGraph.line.js'></script>
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'>
</script>
</head>
<body>
<canvas id='cvs1' width='900' height='300' style='border:solid 1pt red'>
[No canvas support]
</canvas>
<hr>
<canvas id='cvs2' width='900' height='300' style='border:solid 1pt blue'>
[No canvas support]
</canvas>
<script type='text/Javascript'>
drawAll();
$(window).resize(function() {
drawAll();
});
function drawAll() {
var x=150;
var data = [[0, 50, 100, x, 200],[10,20,30,40,50]];
drawChart('cvs1', data);
x=null;
var data = [[0, 50, 100, x, 200],[10,20,30,40,50]];
drawChart('cvs2', data);
}
function drawChart(canvasId, data) {
var canvas = document.getElementById(canvasId);
RGraph.Reset(canvas);
canvas.width = $(window).width() * 0.9;
var text_size = Math.min(10, ($(window).width() / 1000) * 20 );
var linewidth = $(window).width() > 500 ? 2 : 1;
linewidth = $(window).width() > 750 ? 3 : linewidth;
var line = new RGraph.Line(canvasId, data);
line.set('chart.text.size', text_size);
line.Set('chart.background.barcolor1', 'rgba(255,255,255,1)');
line.Set('chart.background.barcolor2', 'rgba(255,255,255,1)');
line.Set('chart.background.grid.color', 'rgba(238,238,238,1)');
line.Set('chart.colors', [ 'red', 'green', 'blue']);
line.Set('chart.linewidth', 1);
line.Set('chart.hmargin', 15);
line.Set('chart.labels', ['Q1\n2017','Q2','Q3','Q4','Q1\n2018']);
line.Set('chart.gutter.left',40);
line.Set('chart.gutter.right',10);
line.Set('chart.gutter.bottom',50);
line.Set('chart.filled', true);
line.Set('chart.filled.accumulative',true);
line.Set('chart.key', ['ABC', 'DEF']);
line.Set('chart.tickmarks.dot.color','white');
line.Set('chart.backgroundGridAutofitNumvlines',data.length);
line.Set('key.position','gutter'); // or graph
line.Set('chart.ymin',0);
line.Set('chart.ymax',250);
line.Set('chart.numyticks',5);
line.Set('chart.key.position.x',50);
line.Set('chart.key.position.y',10);
line.draw();
}
</script>
</body>
</html>
So, how do you tell RGraph to just draw the points with data and ignore those without whilst keeping all the date points?
Thanks
Abe
You can use null values in your data. The behaviour is slightly different for a single dataset vs multiple data sets though:
var data = [4,8,6,3,5,4,2,null,8,6,3,5,8,null,4,9,8];
Well it seems that RGraph doesn't do it, so I've resorted to ChartJS and on the whole it works - see https://jsfiddle.net/Abeeee/6xrk1m23/41/
<script type='text/JavaScript' src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.js'></script>
<div style="width:100%; height:300px">
<canvas id="canvas" style='width:100%; height:300px'></canvas>
</div>
<button id='on'>
Span Gaps=true
</button>
<button id='off'>
Span Gaps=false
</button>
var config = {
type: 'line',
data: {
labels: ['Jan\n2018', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
datasets: [{
label: 'Red',
borderColor: '#FF0000',
backgroundColor: '#FF0000',
data: [
10, 20, 30, 40, 50, 60, undefined, 80, 90, 100, 90, 80
],
}, {
label: 'Blue',
borderColor: '#0000FF',
backgroundColor: '#0000FF',
data: [
10, 20, undefined, 40, 50, 60, 70, 80, 92, undefined, 90, 80
],
}]
},
options: {
spanGaps: true,
responsive: true,
maintainAspectRatio: false,
title: {
display: true,
text: 'Chart.js Line Chart - Stacked Area'
},
tooltips: {
mode: 'index',
},
hover: {
mode: 'index'
},
scales: {
xAxes: [{
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
stacked: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
}
}
};
var ctx1 = document.getElementById('canvas').getContext('2d');
var myChart = new Chart(ctx1, config);
$("#on").on("click", function() {
myChart.options.spanGaps=true;
myChart.update();
});
$("#off").on("click", function() {
myChart.options.spanGaps=false;
myChart.update();
});
Use the buttons to switch spanGaps on and off.
Note, I say on the whole, as it fixes my problem (of underlying data gaps), but it seems to fail to span if the dataset is sitting on top of another (a ChartJS bug perhaps?)

Live streaming data using chart.js, javascript, html

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).

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