Chart-Js x-axis becomes jumbled - javascript

I need to retrieve multiple datapoints from my JSON file and display them on the graph. However, it becomes jumbled around the x-axis, and becomes thin. How do I space these out?
I have
Graph
[
const config = {
type: 'bar',
data,
options: {
scales: {
y: {
beginAtZero: true,
padding: 50
},
x: {
offset: true,
ticks: {
stepSize: 50,
fixedStepSize: 50,
}
}
},
plugins: {
title: {
display: true,
text: 'Worm Egg Count'
},
}
}
};
]2

Related

How to use excess vertical space in stacked bar chart?

I am trying to create a stacked bar chart (with chart.js 3.7+) which uses the entire canvas:
new Chart(..., {
type: 'bar',
data: {
labels: ['a','b','c','d','e'],
datasets: [{
backgroundColor: '#ff00ff',
data: [20,40,60,40,20],
},{
backgroundColor: '#00ff00',
data: [100,200,300,200,100],
}]
},
options: {
maintainAspectRatio: false,
responsive: true,
plugins: {
legend: { display: false },
},
scales: {
x: {
display: false,
stacked: true
},
y: {
display: true,
stacked: true
}
}
}
});
When I use a normal bar chart the graph is stretched to use up all the vertical space:
But when I stack the bars the combined longest bar doesn't use up all the vertical space:
How can I get the stacked bar chart to stretch to use all available vertical space?
See example here.
You could sum your arrays, find the max value in the resulting array and set the options.scales.y.max property with this value :
let data1 = [20,40,60,40,20];
let data2 = [100,200,300,200,100];
let sum = data1.map(function (num, idx) {
return num + data2[idx];
});
let max = Math.max(...sum);
var options =
{
maintainAspectRatio: false,
responsive: true,
plugins: {
legend: { display: false },
},
scales: {
x: {
display: false,
stacked: true
},
y: {
display: true,
stacked: true,
max: max
}
}
};
var mychart = new Chart(document.getElementById('mycanvas2').getContext('2d'), {
type: 'bar',
data: {
labels: ['a','b','c','d','e'],
datasets: [{
backgroundColor: '#ff00ff',
data: data1
},{
backgroundColor: '#00ff00',
data: data2
}]
},
options: options
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<div style="width:400px; height: 200px">
<canvas id="mycanvas2"></canvas>
</div>
According to this issue with chart.js you can configure the y-axis bounds to fit the data:
options: {
scales: {
x: {
display: false,
stacked: true
},
y: {
display: true,
stacked: true,
bounds: 'data' <----------
}
}
}

How do I fix over limit y axis value in ChartJS

Hello Everyone!
I am using chartjs-plugin-datalabels to prevent unhoverable tiny values by displaying the value above his bar, but when one of them has the highest value the datalabels exceed the limit of the chart container
UPDATE:
Also, you can use suggestedMax option and I think it's better than giving a padding
const options = {
plugins: {
datalabels: {
color: '#374774',
font: { family: 'MyriadSemiBold', size: 14 },
align: 'end',
anchor: 'end',
formatter: (value) => {
if (value > 0) {
return localizeNumber(value)
}
return ''
},
},
legend: { display: false },
},
scales: {
x: {
grid: { lineWidth: 0 },
ticks: {
display: false,
},
},
y: {
// Highest value in your datasets
suggestedMax: highestValue > 0 ? highestValue + 1e5 : 10,
grid: { color: '#DFDFDF' },
ticks: {
callback: (value) => {
return abbreviateNumber(value)
},
font: { family: 'MyriadRegular', size: 14 },
color: '#374774',
},
},
},
}
The easiest solution is to add padding to the top of your chart (simple sample below). You may also play around with the datalabel plugin's clamping options to adjust the position of the label when it's outside the chart.
const layoutOptions = {
padding: {
top: 30 // Add 30 pixels of padding to top of chart.
}
};
const data = {
labels: ['Large', 'Small'],
datasets: [{ data: [100, 2] }]
};
const config = {
type: 'bar',
data: data,
options: {
layout: layoutOptions,
scales: { y: { beginAtZero: true, max: 100 } },
plugins: {
legend: { display: false },
datalabels: { anchor: 'end', align: 'top' }
}
},
};
new Chart(document.getElementById('myChart'), config);
#myChart {
max-height: 180px;
}
<div>
<canvas id="myChart"></canvas>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels#2.0.0"></script>
<script>Chart.register(ChartDataLabels);</script>

how to display point circle in a chart with chart.js, when not hovering directly on the line?

I have a chart using chart.js, it's a simple line, and if I hover over the line everything is correct, a circle shows on the point and the tool tip appears.
Now I also wanted that when the user hovers on the X-axis, it would select the circle and show the tooltip for the value at that X-axis point.
So I added this:
tooltips: {
intersect: false,
mode: "index"
}
and it works correctly, now if I hover on the X-axis I'll get the tooltip on my line, but one thing that doesn't work is, I dont get the "circle" on my line, only the tooltip!
I get the circle only if I hover directly on the line, here 2 images so you can see the difference:
in the above image I'm hovering directly on the line, and it shows the Circle and the tooltip
in this image instead I'm hovering on the X-axis and as you can see, it will display only the tooltip on my line, but not the circle!
How can I display the circle even when not hovering directly?
thank you
EDIT: added more code:
ngOnInit(): void {
this.ctx = this.myChartRef.nativeElement.getContext("2d");
this.canvas = new Chart(this.ctx, {
type: "scatter",
data: {
labels: [],
datasets: [
{
label: "Grade",
data: [],
borderColor: "#3cba9f",
fill: false,
pointHitRadius: 10,
showLine: true
}
]
},
options: {
responsive: true,
maintainAspectRatio: true,
elements: {
point: {
radius: 0,
hitRadius: 10,
hoverRadius: 8
}
},
tooltips: {
displayColors: false,
intersect: false,
enabled: true,
mode: "index",
callbacks: {
afterBody: function([tooltipItem], data): any {
const multistringText = ["Points: " + tooltipItem.xLabel];
multistringText.push("Grade: " + tooltipItem.yLabel);
return multistringText;
},
label: function(tooltipItem, data): any {
return;
}
}
},
layout: {
padding: {
top: 12
}
},
legend: {
display: false
},
scales: {
gridLines: {
drawBorder: false
},
xAxes: [
{
ticks: {
beginAtZero: false,
maxTicksLimit: 8,
stepSize: 5,
callback: function(value, index, values): any {
if (Math.floor(value) === value) {
return value;
}
if (value % 5 === 0) {
return value;
}
}
},
scaleLabel: {
display: false
}
}
],
yAxes: [
{
ticks: {
beginAtZero: false,
min: 1,
max: 6
},
scaleLabel: {
display: false
}
}
]
}
}
});
}

How can I remove extra whitespace from the bottom of a line chart in chart.js?

As you can see below with the canvas element highlighted, there is considerable whitespace below the x axis label. If I resize the canvas, the whitespace stays proportional to the height of it. Are there any settings that control this whitespace? I've ruled out padding and do not see any settings for margins.
Thanks!
Here is the JavaScript that renders the chart:
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
options: {
legend: {
display: false
},
elements: {
point: {
radius: 0
}
},
scales: {
xAxes: [{
gridLines: {
display: false,
drawBorder: true
},
ticks: {
autoSkip: true,
maxTicksLimit: 1
}
}],
yAxes: [{
gridLines: {
display: true,
drawBorder: false
},
ticks: {
callback: function(value, index, values) {
return '$' + addCommas(value);
}
}
}]
},
layout: {
padding: 5
}
},
type: 'line',
data: {
labels: labels,
datasets: [
{
data: values,
fill: false,
borderColor: "blue"
}
]
}
});
And the complete jsfiddle: https://jsfiddle.net/rsn288fh/2/
I know you said you ruled out padding, but this is the only option I can see working:
options: {
layout: {
padding: {
bottom: -20
}
}
}
Obviously you can play with the -20 to what works for you.
Here is the reference for padding for chartjs, if you wanted to see more
EDIT:
I've updated your jsfiddle, with a colored div below the chart. As you resize it seems to stay at the same spot below the chart.
Changing the tickMarkLength to 0 results in no padding on the left or bottom of the chart (or wherever your axis happens to be).
https://www.chartjs.org/docs/latest/axes/styling.html#grid-line-configuration
tickMarkLength
Length in pixels that the grid lines will draw into the axis area.
const options = {
scales: {
xAxes: [
{
ticks: {
display: false,
},
gridLines: {
display: false,
tickMarkLength: 0,
},
},
],
yAxes: [
{
ticks: {
display: false,
},
gridLines: {
display: false,
tickMarkLength: 0,
},
},
],
},
};

Changing fontFamily on ChartJS bar chart

I've partially implemented ChartJS in a project, but I can't figure out how to change the font that's displayed on the X and Y axes of a bar chart.
I've read the ChartJS documentation, searched for examples on GitHub, etc. I'm not sure what I'm doing wrong, but I rest assured knowing the solution will involve a line of code and will be a startlingly stupid oversight on my part.
This code draws the chart I want, but with the default font:
var barChartLanguage = Chart.Bar(myCanvas, {
data: dataLanguages,
options: options,
defaults: defaults
});
I tried changing the font in the defaults without success:
var defaults = {
global: {
// example font
defaultFontFamily: "'Raleway'"
}
};
And I tried changing it on the axis with options:
var options = {
animation: {
duration: 2000
},
scales: {
yAxes: [{
display: true,
ticks: {
suggestedMin: 0, // minimum will be 0, unless there is a lower value.
// OR //
beginAtZero: true, // minimum value will be 0.
suggestedMax: 10
},
gridLines: {
display: false
},
pointLabels: {
fontFamily: "'Raleway'"
}
}],
xAxes: [{
gridLines: {
display: false
}
}],
},
};
Add ticks.fontFamily to xAxes so it will look like this:
xAxes: [{
gridLines: {
display: false
},
ticks: {
fontFamily: "Verdana",
}
}],
Documentation: http://www.chartjs.org/docs/#scales
Example on jsfiddle: http://jsfiddle.net/4asLpwd5/
From version 3.x, onwards the syntax was changed.
Chart.js migration guide: 3.x Migration Guide
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
responsive: true,
plugins: {
legend: {
display: false,
}
},
scales: {
x: {
grid: {
display: false
},
ticks: {
font: {
family: 'Raleway', // Your font family
size: 14,
},
},
},
y: {
beginAtZero: true,
ticks: {
font: {
family: 'Raleway', // Your font family
size: 14,
},
// Include a dollar sign in the ticks
callback: function (value, index, values) {
return '$' + value;
},
},
}
}
}
});

Categories