Tick label overlaps axis label - javascript

ChartJS v2
I am having a problem on small screen sizes (using the iPhone 5 screen emulator in Chrome) with my X axis tick labels overlapping my X axis label.
My Y axis label is also being cut off.
I have tried playing around with padding and lineHeight for Label 2 to no avail. I have also tried setting the max / min rotation values for the X axis tick labels to 90deg which makes the issue worse.
The example in the screenshot above uses these settings:
var ctx = document.getElementById("myChart").getContext("2d");
var chart = new Chart(ctx, {
// The type of chart we want to create
type: "bar",
// The data for our dataset
data: {
labels: [
"0k-40k",
"40k-80k",
"80k-100k",
"100k-120k",
"120k-160k",
"160k-180k",
"180k-220k"
],
datasets: [
{
label: "My First dataset",
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgb(255, 99, 132)",
data: [0, 10, 5, 2, 20, 30, 45]
}
]
},
// Configuration options go here
options: {
legend: {
display: false
},
scales: {
xAxes: [
{
ticks: {
autoSkip: false,
fontSize: 16,
fontStyle: "bold",
precision: 2,
suggestedMin: 0
},
scaleLabel: {
display: true,
fontSize: 16,
fontStyle: "bold",
labelString: "Chart Label X",
}
}
],
yAxes: [
{
ticks: {
fontSize: 16,
fontStyle: "bold",
precision: 2,
suggestedMin: 0
},
scaleLabel: {
display: true,
fontSize: 16,
fontStyle: "bold",
labelString: "Chart Label Y",
}
}
]
}
}
});
This looks like it is probably a bug in ChartJS not calculating the label heights correctly when rotated. Has anybody else had this problem? Is there a work around?
Codepen: https://codepen.io/afisher88/pen/mayvoe
GitHub Issue: https://github.com/chartjs/Chart.js/issues/5906

In the end I had to compromise and shrink the font size, removing the x and y labels and updating the legend to provide the detail needed.
var ctx = document.getElementById("myChart").getContext("2d");
var chart = new Chart(ctx, {
// The type of chart we want to create
type: "bar",
// The data for our dataset
data: {
labels: [
"0k-40k",
"40k-80k",
"80k-100k",
"100k-120k",
"120k-160k",
"160k-180k",
"180k-220k"
],
datasets: [
{
label: "My dataset x vs y",
backgroundColor: "rgb(255, 99, 132)",
borderColor: "rgb(255, 99, 132)",
data: [0, 10, 5, 2, 20, 30, 45]
}
]
},
// Configuration options go here
options: {
legend: {
display: true
},
scales: {
xAxes: [
{
ticks: {
autoSkip: false,
fontSize: 11,
fontStyle: "bold",
precision: 2,
suggestedMin: 0
}
}
],
yAxes: [
{
ticks: {
fontSize: 11,
fontStyle: "bold",
precision: 2,
suggestedMin: 0
}
}
]
}
}
});
https://codepen.io/afisher88/pen/XoNVNe

Different browsers can render the canvas image in many different ways. Small screen devices are not an exception. You can try your code with different browsers on normal screen to assert your claim.
Chart.js have many options you can use for your code. i.e. You can use “Chart.bundle.js” or “Chart.js” depending on your environment. The CSS you use can also affect how your chart is rendered on a canvas. The bundled build includes Moment.js in a single file. You should use this version if you require time axes and want to include single file.
For example:
<!DOCTYPE html>
<!--
pcharts.html
-->
<html>
<head>
<title>P Charts</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../public/css/main.css">
<script src="../lib/charts/Chart.bundle.js"></script>
<script src="../lib/jquery/jquery.js"></script>
<script src="../js/appcharts.js"></script>
</head>
<body>
<h1>Charts</h1>
<hr>
<br>
<div id="myCan">
<canvas id="myChart" width="100" height="100"></canvas>
</div>
<br>
<br><br><hr><br><br>
</body>
</html>
appcharts.js
/*
* appcharts.js
*
*/
var ctx;
var myChart;
var cdata = [0, 10, 5, 2, 20, 30, 45];
var lblX = ["0k-40k","40k-80k","80k-100k","100k-120k","120k-160k","160k-180k","180k-220k"];
function init(){
render();
};
function render(){
ctx = document.getElementById("myChart").getContext('2d');
myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: lblX,
datasets: [{
label: 'My demo2 dataset.',
data: cdata,
backgroundColor: [
'rgba(255, 99, 132, 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)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
xAxes: [{
ticks:{
beginAtZero:true
},
scaleLabel:{
display: true,
labelString: "Chart Label X."
}
}],
yAxes: [{
ticks: {
beginAtZero:true
},
scaleLabel: {
display: true,
labelString: "Chart Label Y."
}
}]
}
}
});
};
//
//$(document).ready(function(){
// $("#myCan").hide("slow");
// $("#myCan").show("slow");
//});
//
window.onload = function(){
init();
};
//
//
Squeezing the big image in a small canvas is like squeezing big tomatoes in a small bottle. What will come out of that bottle is the tomato sauce and tomato seeds. Of course you can replant the tomato seeds if only and only if they are still OK. Orthographic projection do just that. You can render a big
image in a small screen by using orthographic projection technique. e.g. Positioning of the camera or distortion determines what the viewer will see or look at.
When you are using charts you are actually drawing an image and rendering it on a screen for the viewer to look at. You can get the latest version of chart.js by using: npm install chart.js --save or download it from: https://github.com/chartjs/Chart.js/releases/latest It comes with docs and samples.
To create a chart, we need to instantiate the Chart class. To do this, we need to pass in the node, jQuery instance, or 2d context of the canvas of where we want to draw the chart. Once you have the element or context, you're ready to instantiate a pre-defined chart-type or create your own.
Good luck.

Related

How to have 0 at the bottom of the canvas [Chart.JS] [duplicate]

I tried every possible way, every form-answer but anything works inmy code. I want yAxes begin at zero and max value is 100 but all my chart begin with other values (see pic). What can I do?
var options = {
responsive: true,
scales: {
yAxes: [{
display: true,
ticks: {
beginAtZero: true,
max: 100,
min: 0
}
}]
},
title: {
display: true,
text: name
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
};
key is to pass options in the Chart constructor instead of part of data
new Chart(ctx, {
type: 'bar',
data: {{ chart_data|safe }},
options: {
scales: {
yAxes: [{
display: true,
ticks: {
beginAtZero: true
}
}]
}
}
});
above works for me!
#Nikolas,
Here is the fiddle where the parameters you set works well.
https://jsfiddle.net/shemdani/zkb215up/2/
var options = {
responsive: true,
scales: {
yAxes: [{
display: true,
ticks: {
beginAtZero: true,
max: 100,
min: 0
}
}]
},
title: {
display: true,
text: name
},
tooltips: {
mode: 'index',
intersect: false,
},
hover: {
mode: 'nearest',
intersect: true
},
};
var data = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [32, 59, 36, 25, 68, 71],
backgroundColor: [
'rgba(255, 99, 132, 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)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
}
var ctx = document.getElementById("myChart");
var chartInstance = new Chart(ctx, {
type: 'line',
data: data,
options:options
});
Please check and see what you are doing wrong. I used the basic data from charjs documentation.
Working for version 3.2.0:
var options = {
// plugins, responsive etc...
scales: {
y: {
min: 0
}
},
//tooltips specifications...
}
The y-axis will start at 0:
I tried different solutions and adding barThickness: 25 in options worked for me.

How to hide grid lines and x-axis labels in chart.js?

I'm using chart.js v3.2.0 and I want to disable the grid lines and x-axis labels. I've tried various examples from other stack overflow posts but none seem to work.
https://jsfiddle.net/gcp95hjf/1/
html
<div style = "width: 600px; height: 400px;">
<canvas id="chartJSContainer" width="1" height="400"></canvas>
</div>
js
var options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderWidth: 1,
backgroundColor: 'rgba(255, 99, 132, 0.2)',
borderColor: 'rgba(255, 99, 132,1)'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderWidth: 1,
backgroundColor: 'rgba(54, 162, 235, 0.2)',
borderColor: 'rgba(54, 162, 235, 1)'
}
]
},
options: {
scales: {
xAxes: [{
display: false,
ticks: {
display: false //this will remove only the label
}
}],
yAxes: [{
display:false
}]
},
responsive: true,
maintainAspectRatio: false
}
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
Does anyone know how to do it?
Thanks
Chart.js v3 has multiple breaking changes, one of them is how you define the scales, it is stated in the migration guide and shown in a lot of the examples (https://www.chartjs.org/docs/3.2.1/getting-started/v3-migration.html)
You will have to change scales: { yAxes: [], xAxes: []} to scales: { y: {}, x: {}}
Working fiddle: https://jsfiddle.net/Leelenaleee/r26h71fm/2/
Hide GridLines on Both Axis -
ChartJS v2 (older version) -
scales: {
x: [
{
gridLines: {
display: false,
},
},
],
y: [
{
gridLines: {
display: false,
},
},
],
},
Newer Version ChartJS v3 -
scales: {
x: {
grid: {
display: false,
},
},
y: {
grid: {
display: false,
},
},
},

How do I access data in an array in an external javascript file to use in a chart using chart.js?

function getWeeklyPay(soc){
$.ajax({
url: "http://api.lmiforall.org.uk/api/v1/ashe/estimatePay?soc=".concat(soc),
type: "get",
dataType: "json",
success: function(data){
var xYears = [];
var yPay = [];
console.log(data);
for(let i=0; i<data.series.length; i++){
xYears.push(data.series[i].year);
yPay.push(data.series[i].estpay);
}
console.log(xYears);
console.log(yPay);
}
});
}
My code above gives me the following values
And I would like to use this data for my x and y axis on my chart.js as well as the data for the chart but I don't know how to access the data on my HTML page.
Any help would be great thanks
its quite easy, i did it like this for line chart,
<div class="chartCase">
<canvas id="cases"></canvas>
</div>
you need this ^ for your html, you can css chartCase for propr width and height, and chart data will be as following ,
let caseChart= document.getElementById("cases").getContext("2d");
let charts = new Chart(caseChart,{
type: "line",
responsive: true, // if you wnat it to be responsive
//- Data layer start
data: {
//- Labels
labels: X Data here,
//- Datasets
datasets: [
{
data: Y Data here ,
label: "Your Label Name",
backgroundColor: "rgba(54, 162, 235, 0.2)", // line color
borderColor: "rgba(54, 162, 235, 1)",
},
],
};
//- Data layer end
//- Options Start
options: {
legend: {
display: true, // if you dont want legends Write False
position: "top", // legends position
labels: { // legends label fontsize+ padding
fontSize: 14,
padding: 4,
},
},
scales: { // customizing X axis and Y axis
xAxes: [
{
gridLines: { // this is for X axis grid lines
color: "rgba(0, 0, 0, 0)",
},
},
],
yAxes: [
{
ticks: { // if you want to customize your Y axis
fontSize: 16,
beginAtZero: true,
callback: function (value) {
// if you want a custom function write here.
},
},
},
],
},
},
//- Options end
});
`
the same thing for the bar chart, also, if you want more datasets just do this
datasets: [
{
data: First data here,
label: "first label",
backgroundColor: "rgba(54, 162, 235, 0.2)",
borderColor: "rgba(54, 162, 235, 1)",
},
{
data: Second data here,
label: "second label",
backgroundColor: "rgba(214, 102, 121, 0.3)",
borderColor: "rgba(214, 102, 121, 1)",
},
{
data: third data here,
label: "third label",
backgroundColor: "rgba(113, 255, 47, 0.2)",
borderColor: "rgba(113, 255, 47, 1)",
},
if you want any other chart check their documentation, https://www.chartjs.org/docs/latest/getting-started/

Trying to insert another label for a piechart in ChartsJS

I created this piechart using chartsjs. As of now, if you run the snippet, I am able to display my labels the following way:
Uno\Company 1
19
(56%)
However, I would love to display Company text underneath, so that it can be displayed like this:
Uno
Company1
19
(56%)
I tried creating a separate array: label2: ["Company1", "Company2", "Company3"]
Then in the callback, I added a new function, which i thought would give me the other label beneath, but no luck. Here is the code I used for that:
title2: function(tooltipItem, data, label2){
return data['label2'][tooltipItem[0]['index']]
}
Can anyone help me out?
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
label1: ["Uno\\Company1", "Dos\\Company2", "Tres\\Company3"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 1
}]
},
options: {
tooltips: {
callbacks: {
title: function(tooltipItem, data, label1, label2) {
return data ['label1'][tooltipItem[0]['index']];
},
label: function(tooltipItem, data) {
return data['datasets'][0]['data'][tooltipItem['index']];
},
afterLabel: function(tooltipItem, data) {
var dataset = data['datasets'][0];
var percent = Math.round((dataset['data'][tooltipItem['index']] / dataset["_meta"][0]['total']) * 100)
return '(' + percent + '%)';
}
},
backgroundColor: '#FFF',
titleFontSize: 16,
titleFontColor: '#0066ff',
bodyFontColor: '#000',
bodyFontSize: 14,
displayColors: false
}
}
});
<div>
<canvas id="myChart" height="100"></canvas>
<div id="chartjs-tooltip">
<table></table>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js">
</script>
Simply change label1 from an array of strings to an array of arrays:
label1: [["Uno", "Company1"], ["Dos", "Company2"], ["Tres", "Company3"]]
Chart.js will treat separate array items as separate lines.

Label is too long in Doughnut Chart

I try to display a Doughnut Chart with the chart.js library.
Here is the code that I am using:
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: ['long long long long long long title', 'title', 'title', 'title', 'title'],
datasets: [{
data: [54,36,12,4,20],
backgroundColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
}]
},
options: {
legend: {
display: true,
position: 'bottom',
labels: {
fontColor: 'rgb(0, 0, 0)',
fontFamily: 'Open Sans',
fontSize: 16,
fullWidth: true,
padding:15
}
}
}
});
I have the problem that for a certain page width the long long ... long title is not correctly displayed.
In some situations it looks like this:
Is there anything I can do so that the long label will be shown in multiple lines instead of leaving the box?
Here is a jsfiddle
https://jsfiddle.net/9fc5evjk/
This is not supported "out of the box" by chart.js. You will need to determine what solution works best for you and implement it yourself. You will need to provide modified strings to the instantiation of myChart.
You could automatically truncate a title after X number of characters, maybe add a '...' to the end when it happens to make it obvious when a title has been shortened.

Categories

Resources