How to set ChartJS Y axis title? - javascript

I am using Chartjs for showing diagrams and I need to set title of y axis, but there are no information about it in documentation.
I need y axis to be set like on picture, or on top of y axis so someone could now what is that parameter
I have looked on official website but there was no information about it

In Chart.js version 2.0 this is possible:
options = {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
See axes labelling documentation for more details.

For Chart.js 2.x refer to andyhasit's answer - https://stackoverflow.com/a/36954319/360067
For Chart.js 1.x, you can tweak the options and extend the chart type to do this, like so
Chart.types.Line.extend({
name: "LineAlt",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var ctx = this.chart.ctx;
ctx.save();
// text alignment and color
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
ctx.fillStyle = this.options.scaleFontColor;
// position
var x = this.scale.xScalePaddingLeft * 0.4;
var y = this.chart.height / 2;
// change origin
ctx.translate(x, y);
// rotate text
ctx.rotate(-90 * Math.PI / 180);
ctx.fillText(this.datasets[0].label, 0, 0);
ctx.restore();
}
});
calling it like this
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).LineAlt(data, {
// make enough space on the right side of the graph
scaleLabel: " <%=value%>"
});
Notice the space preceding the label value, this gives us space to write the y axis label without messing around with too much of Chart.js internals
Fiddle - http://jsfiddle.net/wyox23ga/

For x and y axes:
options : {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}],
xAxes: [{
scaleLabel: {
display: true,
labelString: 'hola'
}
}],
}
}

For Chart.js 3.x
options: {
scales: {
y: {
title: {
display: true,
text: 'Y axis title'
}
}
}
}

chart.js supports this by defaul check the link.
chartjs
you can set the label in the options attribute.
options object looks like this.
options = {
scales: {
yAxes: [
{
id: 'y-axis-1',
display: true,
position: 'left',
ticks: {
callback: function(value, index, values) {
return value + "%";
}
},
scaleLabel:{
display: true,
labelString: 'Average Personal Income',
fontColor: "#546372"
}
}
]
}
};

For me it works like this:
options : {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}

Consider using a the transform: rotate(-90deg) style on an element.
See http://www.w3schools.com/cssref/css3_pr_transform.asp
Example,
In your css
.verticaltext_content {
position: relative;
transform: rotate(-90deg);
right:90px; //These three positions need adjusting
bottom:150px; //based on your actual chart size
width:200px;
}
Add a space fudge factor to the Y Axis scale so the text has room to render in your javascript.
scaleLabel: " <%=value%>"
Then in your html after your chart canvas put something like...
<div class="text-center verticaltext_content">Y Axis Label</div>
It is not the most elegant solution, but worked well when I had a few layers between the html and the chart code (using angular-chart and not wanting to change any source code).

Related

chartjs: need color bars near yAxis scale

I would like to achieve something like the below image.
Chart with color band in yAxis
I already have working version of line chart in different places in our application. In One place we need a chart with color band in yAxis. Somehow I achieved this result StackBlitz Example
But the problems are
Not able to adjust the width of the bar
Not able to move the position of the bar close to yAxis
You can define a separate x-axis for the bar and name it "bar-x-axis" for example. The important thing is to define offset: false, ticks.display: false and gridLines.display: false.
xAxes: [{
stacked: true
},
{
id: "bar-x-axis",
offset: false,
stacked: true,
ticks: {
display: false
},
gridLines: {
display: false
}
}
]
Your bar datasets are linked to this new x-axis through the option xAxisID: "bar-x-axis" . To change the width of the bars, you would define a value between below 1 for barPercentage.
{
label: "Low-Moderate",
backgroundColor: "#ffe100",
yAxisID: "bar-y-axis",
xAxisID: "bar-x-axis",
data: [20],
barPercentage: 0.5
}
Please have a look at your amended StackBlitz.
You can draw individual boxes directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.
First, you would define the color bars in an array as follows:
const colorBars = [
{ y: 20, color: "#aad700" },
{ y: 40, color: "#ffe100" },
{ y: 60, color: "#ef0000" },
{ y: 80, color: "#aad700" },
{ y: 100, color: "#ffe100" }
];
Then you can define a plugin with the beforeDraw hook as shown below:
const plugins = [
{
beforeDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales["x-axis-0"];
var yAxis = chart.scales["y-axis-0"];
ctx.save();
var prevY = 0;
colorBars.forEach((c, i) => {
ctx.fillStyle = c.color;
ctx.beginPath();
var yBottom = yAxis.getPixelForValue(prevY);
var yTop = yAxis.getPixelForValue(c.y);
ctx.fillRect(xAxis.left - 10, yTop, 10, yBottom - yTop);
ctx.stroke();
prevY = c.y;
});
ctx.restore();
}
}
];
The drawback of this solution is, that you won't see a tooltip when the mouse pointer hovers over the bars.
Please have a look at your amended StackBlitz and see how it works.

How can I remove the grid lines in Chart.js

I'm using charts in my react app. I tried using the Scales and gridlines: false option but it is not working from me.
the image shows my code.
Thank you.
You might check a chart.js sample. From there I found some deviations in the object setup of your example
var config = {
type: 'line',
data: {
datasets: [{
// Here starts your snippet
}]
},
options: {
// The options are outside of the datasets property
scales: {
x: {
gridLines: {
display: false
}
},
y: {
gridLines: {
display: false
}
}
}
}
};
Edit 1: updated the scales with the gridLines property
You can use below code to remove gridlines and if you want to enable X and Y axis its useful
gridLines: {
display: true,
zeroLineColor:'white',
color:'transparent'
}

Horizontal xAxis labels in Chart.js

I'm working with a chart-js bar chart that has to be placed inside a small div so I was searching for a way to make the labels in the x-axis horizontal instead of diagonal. The point is to gain as much height as possible for the actual bars because right now the labels consume almost 40% of the available space.
This is my code:
let options = {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
display: false
}]
}
};
let ctx = document.getElementById('barChartCtx');
let barChart = new Chart(ctx, {
type: 'bar',
data: data,
options: options
});
I have temporarily disabled the xAxis labels. It works but ideally I would like them to be horizontal. Thoughts?
You can use the scale ticks maxRotation and minRotation properties to control this.
Here is an example.
let options = {
responsive: true,
maintainAspectRatio: false,
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}],
xAxes: [{
ticks: {
minRotation: 0,
maxRotation: 0
}
}]
}
};
Keep in mind that the reason they are diagonal is because chart.js calculated that they would not fit at their default horizontal orientation. If you find that they overflow on each other when horizontal then you can still use the above properties to tweak the rotation so they are only slightly diagonal.

Bar chart legend adjustments - Chart JS

I'm new in Chart JS and I have a bar chart with the legend displayed bellow the chart:
var data = {
labels: [],
datasets: [{
label: 'Disk C',
backgroundColor: "#000080",
data: [80]
}, {
label: 'Disk D',
backgroundColor: "#d3d3d3",
data: [90]
},
{
label: 'Memory',
backgroundColor: "#add8e6",
data: [45]
}]
};
var ctx = document.getElementById("mybarChart");
ctx.height = 300;
var mybarChart = new Chart(ctx, {
type: 'bar',
responsive: true,
data: data,
options: {
legend: {
display: true,
position: 'bottom'
},
scales: {
yAxes: [{
display: false,
ticks: {
beginAtZero: true
},
gridLines: {
color: "rgba(0, 0, 0, 0)",
}
}],
xAxes: [{
display: false,
gridLines: {
color: "rgba(0, 0, 0, 0)",
},
barPercentage: 0.5,
categoryPercentage: 0.5
}]
}
}
});
But the legend should be something like :
It is possible to make the colors rectangles much more smaller and the values to be displayed one below another because in my example the labels are displayed in a single row?
Unfortunately, there is no way to customize the default legend in the manner that you are wanting. Fortunately, however, chart.js thought of this and provided a mechanism for you to generate and style your own legend outside of the canvas object (using regular html/css).
You can use the legendCallback options property to define a method that generates your legend html and then call the chart .generateLegend() prototype method to place into your page. Here is what I mean.
HTML for my page.
<div style="width:25%;">
<canvas id="mybarChart"></canvas>
<div id="legend"></div>
</div>
Then I define how the legend will look in the 'legendCallback' option property.
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
for (var i = 0; i < chart.data.datasets.length; i++) {
text.push('<li><div class="legendValue"><span style="background-color:' + chart.data.datasets[i].backgroundColor + '"> </span>');
if (chart.data.datasets[i].label) {
text.push('<span class="label">' + chart.data.datasets[i].label + '</span>');
}
text.push('</div></li><div class="clear"></div>');
}
text.push('</ul>');
return text.join('');
}
Finally, I add the legend html to my page.
$('#legend').prepend(mybarChart.generateLegend());
As always, here is a codepen example showing a working solution. You can change your legend look and feel simply by changing the html that is generated by the callback and using css.

Chart.js line chart is cut off at the top?

For some reasone all graphs are cut off at the highest value.
How can i fix this? I can't use a fixed y-axis
Edit/Update: As mentioned in the comments, the 5px value can more accurately be just half of whatever your line width value is, I belive default is 2px so in that case you would just want padding: { top: 1 }
There a layout.padding attribute you can set either in options or global. I had this same problem and set
options: {
layout: {
padding: {
top: 5
}
},
...
}
worked fine for me to not cut off the line
http://www.chartjs.org/docs/#chart-configuration-layout-configuration
I used hardcode, just wide draw area at top and bottom. This code based on original Chart.canvasHelpers.clipArea.
const WIDE_CLIP = {top: 2, bottom: 4};
Chart.canvasHelpers.clipArea = function(ctx, clipArea) {
ctx.save();
ctx.beginPath();
ctx.rect(
clipArea.left,
clipArea.top - WIDE_CLIP.top,
clipArea.right - clipArea.left,
clipArea.bottom - clipArea.top + WIDE_CLIP.bottom
);
ctx.clip();
};
You can try clip:false option, worked for me.
Example:
options: {
clip: false,
responsive: true,
interaction: {
intersect: false,
mode: 'index',
}
}
I found this while making line graphs that had the legend displayed at the top. The only work around I found was to move the legend to the bottom
options: {
legend: {
position: 'bottom',
},
}
fiddle
I ran into this Chart.js bug, too.
A very recent fix is shown here.
You'd have to manually edit your Chart.js file src/controllers/controller.line.js
(For Angular 2, this file path will be located inside directory node_modules/chart.js/.)
Or just wait for the next Chart.js release which will most likely contain the fix.
An alternative workaround is described in comment 1 of this bug ticket:
https://github.com/chartjs/Chart.js/issues/4202
The options.layout.padding.top solution didn't work for me (just added padding AFTER the line cut), so I extracted the high/low values from my data and used the suggestedMin and suggestedMax config params like this:
var suggestedMin = {MIN};
var suggestedMax = {MAX};
options: {
scales: {
yAxes: [{
ticks: {
suggestedMin: suggestedMin - 1,
suggestedMax: suggestedMax + 1,
}
}]
}
}
This issue has been fixed in the Chart.js library. Just update it and you'll be fine.
I had my data values stored in array. So I set my max and min values like this:
var _array = [1,3,2];
var suggestedMax = Math.max.apply(Math,_array); // 3
var suggestedMin = Math.min.apply(Math,_array); // 1
And than you can set
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false,
suggestedMin: suggestedMin - 1,
suggestedMax: suggestedMax + 1,
}
}]
}
}
And it works, thank you.

Categories

Resources