Chartjs fixed range on X axis and custom labels - javascript

I'm trying to create a scatter plot with Chartjs.
I want to have few datasets centered around one X value, and three Y values.
When I can't set the custom X labels for my dataset, and also can't set a fixed range for X axes.
This is how I generate the data:
function generateData(n, xCenter, yCenter) {
var data = [];
var spread = 0.2
for (var i = 0; i < n; i++) {
data.push({
x: (Math.random() - 0.5)*spread + xCenter,
y: (Math.random() - 0.5)*spread + yCenter
})
}
return data
}
var scatterChartData = {
datasets: [
{
label: 'My First dataset',
backgroundColor: "#0000FF",
data: generateData(100, 1, 2)
},
{
label: 'My Second dataset',
backgroundColor: "#00FF00",
data: generateData(50, 1, 3)
},
{
label: 'My Second dataset',
backgroundColor: "#00FF00",
data: generateData(50, 1, 4)
},
]
}
Here are the scatter options:
var scatterOptions = {
tooltips: {
enabled: true
},
responsive: true, // Instruct chart js to respond nicely.
maintainAspectRatio: false, // Add to prevent default behaviour of full-width/height
responsive: true,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
display: false,
ticks: {
min: 0,
max: 10,
stepSize: 0.01
}
}
}],
yAxes: [{
gridLines: {
display: true,
ticks: {
stepSize: 0.01,
suggestedMin: 0.5,
suggestedMax: 5
}
}
}]
}
}
And this is the plot:
var myChart = new Chart(ctx, {
showTooltips: false,
type: 'scatter',
data: scatterChartData,
options: scatterOptions
});

Related

change axis scale to be round numbers instead of decimal - chart.js

I'm working with chart.js and I can't seem to be able to change the scale of the Y axis to show whole numbers, in this example I would like to have just round numbers in the scale (1,2,3,4,5) instad of the decimal (0 -0,5 - 1,0 - 1,5 - 2,0 - etc)
I'm using a vertical Bar chart from here: https://www.chartjs.org/docs/latest/samples/bar/vertical.html
and my current setup is this:
var setVirtualBarChart = function (element, viewModel) {
var chArea = element.getContext("2d");
var chartConfig = {
type: 'bar',
data: {
labels: ['Categories'],
datasets: [
{
minBarLength: 2,
label: '0-7 days',
barPercentage: 0.75,
categoryPercentage: 0.75,
data: viewModel.ZeroToSevenDaysUser(),
backgroundColor: window.chartColors.BrightVisibleGreen
},
{
minBarLength: 2,
label: '8-30 days',
barPercentage: 0.75,
categoryPercentage: 0.75,
data: viewModel.SevenToThirtyDaysUser(),
backgroundColor: window.chartColors.Orange
},
{
minBarLength: 2,
label: '30+ test days',
barPercentage: 0.75,
categoryPercentage: 0.75,
data: viewModel.ThirtyPlusDaysUser(),
backgroundColor: window.chartColors.BrightRed
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [
{
stacked: false,
display: true,
scaleLabel: {
display: true,
//labelString: 'Categories',
gridLines: {
offsetGridLines: true
}
}
}
],
yAxes: [
{
stacked: false,
display: true,
scaleLabel: {
display: true,
labelString: 'Number of invoices'
},
ticks: {
precision: 0,
min: 0
}
}
]
}
}
};
VirtualBarChart = new Chart(chArea, chartConfig);
};
You are using v2 syntax while using v3, in v3 all scales are objects and no arrays anymore. For all changes please read the migration guide
Exaple:
const options = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow"],
datasets: [{
label: '# of Votes',
data: [1, 2.5, 1.5],
backgroundColor: ["Red", "Blue", "Yellow"]
}]
},
options: {
scales: {
y: {
ticks: {
stepSize: 1
},
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

ChartJS makes unwanted horizontal line on Safari

I'm currently working with ChartJS.
It works fine on Firefox and Chrome.
On Safari there is horizontal lines which appear. (here there is one good on orange and two others unwanted )
I have a lot of datapoint (2 lines of 1600 data point). I don't know if it could be a cause.
My code is here.
In some other part, I update time uni and time min.
_displayChart: function(label1, label2){
var timeFormat = 'DD/MM/YYYY HH:mm';
var ctx = document.getElementById(this.heading).getContext('2d');
const data = {
// Labels should be Date objects
//labels:this._stats[1],
datasets: [{
fill: false,
label: label1,
data: this._stats[2],
borderColor: '#fe8b36',
pointRadius: 0,
backgroundColor: [
'#fe8b36'
]
},{
label: label2,
fill: false,
data: this._stats[3],
borderWidth: 1,
pointRadius: 0,
borderColor: 'rgba(99, 100, 200, 1)',
backgroundColor: [
'rgba(99, 100, 200, 0.2)'
]
}]
}
const options = {
type: 'line',
data: data,
options: {
responsive: false,
fill: false,
responsive: true,
maintainAspectRatio:!this._isMobile(),
max: this.max,
hover: {
// Overrides the global setting
mode: 'index'
},
annotation: {
drawTime: 'beforeDatasetsDraw',
events: ['click'],
annotations: []
},
legend: {
labels: {
filter: function(legendItem, chartData) {
if(legendItem.datasetIndex == 2 || legendItem.datasetIndex == 3 ){
return false;
}
return true;
}
}
},
tooltips: {
mode:'index',
intersect : false,
callbacks: {
title: function(tooltipItems, data) {
return tooltipItems[0].xLabel.format(timeFormat);
},
label: function(tooltipItems, data) {
return tooltipItems.yLabel+'%';
}
}
},
scales: {
xAxes: [{
type: 'time',
display: true,
time:{
unit:'day',
min:moment(Date.now()-this.monthTs),
max:this._stats[1][this._stats[1].length]
}
}],
yAxes: [{
ticks: {
beginAtZero: true,
},
display: true
}]
}
}
}
this._chart = new Chart(ctx, options);
},
When I'm applying this, I have no problem:
this._chart.options.scales.xAxes[0].time.unit = 'month';
this._chart.options.scales.xAxes[0].time.stepSize = 1;
this._chart.options.scales.xAxes[0].time.min = this._stats[1][0];
this._chart.options.scales.xAxes[0].time.max = this._stats[1][this._stats[1].length-1];
Thanks

Edit styles for axes in ChartJS bar chart, when gridlines are hidden

I have a bar chart with gridlines displayed to false. Now, I need to set the width and color, only for the axis lines (x and y). I can set these values as:
options:{
scales: {
xAxes: [{
gridLines: {
color: "rgba(0,0,0,1)",
lineWidth: 1
}
}],
yAxes: [{
gridLines: {
color: "rgba(0,0,0,1)",
lineWidth: 1
}
}],
}
}
However, when I want to hide the gridlines, I am unable to set the styling (width or color) , only for the axes.
options:{
scales: {
xAxes: [{
gridLines: {
display:false
}
}],
yAxes: [{
gridLines: {
display:false
}
}],
}
}
I have tried scaleLineColor but that too didn't seem to work. Here is my full code:
var q1 = document.getElementById("q1").getContext('2d');
var q1Chart = new Chart(q1, {
type: 'bar',
data: {
labels: ["Very Good(9-10)","Good(8-7)","OK(5-6)","Bad (3-4)","Cant be worse (0-2)"],
datasets: [{
label: "Our Performance",
data: [19.56,37.90,1.29,30.36,10.89],
backgroundColor: ["#d93030","#288fba","#367fa9","#367fa9","#367fa9"],
datalabels: {
align: 'top',
anchor: 'end',
font: {
size: 18,
weight: 900,
},
formatter: function(value) {
var label = value;
var keys, klen, k;
return label + '%';
}
}
}]
},
scaleLineColor: "rgba(0,0,0,1)",
options:{
scales: {
xAxes: [{
barThickness : 50,
ticks: {
fontColor: "black",
fontSize: 20,
autoSkip: false,
},
gridLines: {
display:false
}
}],
yAxes: [{
ticks: {
fontColor: "black",
fontSize: 20,
beginAtZero: true,
stepSize: 10
},
gridLines: {
display:false
}
}],
},
responsive: false,
maintainAspectRatio: true,
legend: {
display: false
},
tooltips: {
enabled: false
},
layout: {
padding: {
left: 0,
right: 0,
top: 30,
bottom: 0
}
}
},
});
The only way I know to do this, is to write a plugin to do it
Chart.pluginService.register({
afterDraw: function (chart, easing) {
if (chart.config.options && chart.config.options.scales) {
if (chart.config.options.scales.xAxes)
chart.config.options.scales.xAxes.forEach(function (xAxisConfig) {
if (!xAxisConfig.color)
return;
var ctx = chart.chart.ctx;
var chartArea = chart.chartArea;
var xAxis = chart.scales[xAxisConfig.id];
// just draw the scale again with different colors
var color = xAxisConfig.gridLines.color;
xAxisConfig.gridLines.color = xAxisConfig.color;
xAxis.draw(chartArea);
xAxisConfig.gridLines.color = color;
});
if (chart.config.options.scales.yAxes)
chart.config.options.scales.yAxes.forEach(function (yAxisConfig) {
if (!yAxisConfig.color)
return;
var ctx = chart.chart.ctx;
var chartArea = chart.chartArea;
var yAxis = chart.scales[yAxisConfig.id];
var color = yAxisConfig.gridLines.color;
yAxisConfig.gridLines.color = yAxisConfig.color;
yAxis.draw(chartArea);
yAxisConfig.gridLines.color = color;
ctx.restore();
});
}
}
});
Chart.pluginService.register({
afterDraw: function (chart, easing) {
if (chart.config.options && chart.config.options.scales) {
if (chart.config.options.scales.xAxes)
chart.config.options.scales.xAxes.forEach(function (xAxisConfig) {
if (!xAxisConfig.color)
return;
var ctx = chart.chart.ctx;
var chartArea = chart.chartArea;
var xAxis = chart.scales[xAxisConfig.id];
// just draw the scale again with different colors
var color = xAxisConfig.gridLines.color;
xAxisConfig.gridLines.color = xAxisConfig.color;
xAxis.draw(chartArea);
xAxisConfig.gridLines.color = color;
});
if (chart.config.options.scales.yAxes)
chart.config.options.scales.yAxes.forEach(function (yAxisConfig) {
if (!yAxisConfig.color)
return;
var ctx = chart.chart.ctx;
var chartArea = chart.chartArea;
var yAxis = chart.scales[yAxisConfig.id];
var color = yAxisConfig.gridLines.color;
yAxisConfig.gridLines.color = yAxisConfig.color;
yAxis.draw(chartArea);
yAxisConfig.gridLines.color = color;
ctx.restore();
});
}
}
});
var q1 = document.getElementById("q1").getContext('2d');
var q1Chart = new Chart(q1, {
type: 'bar',
data: {
labels: ["Very Good(9-10)", "Good(8-7)", "OK(5-6)", "Bad (3-4)", "Cant be worse (0-2)"],
datasets: [{
label: "Our Performance",
data: [19.56, 37.90, 1.29, 30.36, 10.89],
backgroundColor: ["#d93030", "#288fba", "#367fa9", "#367fa9", "#367fa9"],
datalabels: {
align: 'top',
anchor: 'end',
font: {
size: 18,
weight: 900,
},
formatter: function (value) {
var label = value;
var keys, klen, k;
return label + '%';
}
}
}]
},
scaleLineColor: "rgba(0,0,0,1)",
options: {
scales: {
xAxes: [{
color: 'yellow',
barThickness: 100,
ticks: {
fontColor: "black",
fontSize: 20,
autoSkip: false,
},
gridLines: {
display: false
}
}],
yAxes: [{
color: 'yellow',
barThickness: 150,
ticks: {
fontColor: "black",
fontSize: 20,
beginAtZero: true,
stepSize: 10
},
gridLines: {
display: false
}
}],
},
responsive: true,
maintainAspectRatio: true,
legend: {
display: false
},
tooltips: {
enabled: false
},
layout: {
padding: {
left: 0,
right: 0,
top: 30,
bottom: 0
}
}
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.js"></script>
<canvas id="q1" height=""></canvas>

how to change the Y-axis values from float number to integer in chartjs?

i want to change Yaxis from real number to integer and here is image, and please help me solve this problem
here is my code
var lineChartData = {
labels: time,
datasets: [{
label: "Số người đăng kí ủng hộ",
borderColor: window.chartColors.red,
pointBackgroundColor: window.chartColors.red,
fill: false,
data: people_isProcessing
}, {
label: "Số người đã ủng hộ",
borderColor: window.chartColors.purple,
pointBackgroundColor: window.chartColors.purple,
fill: false,
data: people_isReceived
}]
};
and here is my option for my chart
window.onload = function() {
var chartEl = document.getElementById("chart");
window.myLine = new Chart(chartEl, {
type: 'line',
data: lineChartData,
options: {
title: {
display: true,
text: 'Kindmate - Chart Static Donate'
},
tooltips: {
enabled: true,
mode: 'index',
position: 'nearest',
custom: customTooltips
}
}
});
});
In your case, you can set stepSize property to 1 for y-axis ticks, to change the y-axis values from float number to integer.
options: {
scales: {
yAxes: [{
ticks: {
stepSize: 1
}
}]
},
...
}
ᴅᴇᴍᴏ
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ['Jan', 'Feb', 'Mar', 'Apr'],
datasets: [{
label: '# of votes',
data: [1, 2, 3, 4]
}]
},
options: {
scales: {
yAxes: [{
ticks: {
stepSize: 1
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="ctx"></canvas>
Try this:
window.onload = function() {
var chartEl = document.getElementById("chart");
window.myLine = new Chart(chartEl, {
type: 'line',
data: lineChartData,
options: {
title:{
display:true,
text:'Kindmate - Chart Static Donate'
},
tooltips: {
enabled: true,
mode: 'index',
position: 'nearest',
custom: customTooltips
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value) {if (value % 1 === 0) {return value;}}
}
}]
}
}
});

chart.js v2: Align time scale labels with the center of the bars

I am trying to align the generated time scale labels using Chart.js v2.2 with the centre of the bars of a bar chart. I have tried the offsetGridLines option but this seems to have no effect when using Xaxis scale type time.
Here is an example, maybe I have missed something:
<div id="container" style="width: 75%;">
<canvas id="canvas"></canvas>
</div>
<script>
var barChartData = {
labels: ["2015-01-01", "2015-02-01", "2015-03-01", "2015-04-01", "2015-05-01", "2015-07-01"],
datasets: [{
label: 'Dataset 1',
backgroundColor: "rgba(220,220,220,0.5)",
data: [10, 4, 5, 7, 2, 3]
}]
};
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
elements: {
rectangle: {
borderWidth: 2,
borderColor: 'rgb(0, 255, 0)',
borderSkipped: 'bottom'
}
},
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Bar Chart'
}
,
scales: {
xAxes: [{
categoryPercentage: .5,
barPercentage: 1,
type: 'time',
scaleLabel: {
display: true,
labelString: 'Year-Month'
},
time: {
min: '2014-12-01' ,
max: '2015-12-01',
unit: 'month',
displayFormats: {
month: "MMM YY"
}
},
gridLines: {
offsetGridLines: false,
drawTicks: true,
display: true
},
stacked: true
}],
yAxes: [{
ticks: {
beginAtZero: true
},
stacked: true
}]
}
}
});
};
</script>
This fiddle may help to place the data label in the center of the bar
https://jsfiddle.net/tea8dhgy/
<div id="container" style="width: 75%;">
<canvas id="canvas"></canvas>
</div>
var barChartData = {
labels: ["2015-01-01", "2015-02-01", "2015-03-01", "2015-04-01", "2015-05-01", "2015-07-01"],
datasets: [{
label: 'Dataset 1',
backgroundColor: "rgba(220,220,220,0.5)",
data: [10, 4, 5, 7, 2, 3]
}]
};
var ctx = document.getElementById("canvas").getContext("2d");
new Chart(ctx, {
type: 'bar',
data: barChartData,
options: {
elements: {
rectangle: {
borderWidth: 2,
borderColor: 'rgb(0, 255, 0)',
borderSkipped: 'bottom'
}
},
responsive: true,
legend: {
position: 'top',
},
title: {
display: true,
text: 'Chart.js Bar Chart'
},
scales: {
xAxes: [{
categoryPercentage: .5,
barPercentage: 1,
type: 'time',
scaleLabel: {
display: true,
labelString: 'Year-Month'
},
time: {
// min: '2014-12-01' ,
// max: '2015-12-01',
unit: 'month',
displayFormats: {
month: "MMM YY"
}
},
gridLines: {
offsetGridLines: false,
drawTicks: true,
display: true
},
stacked: true
}],
yAxes: [{
ticks: {
beginAtZero: true
},
stacked: true
}]
},
animation: {
onComplete: function() {
var chartInstance = this.chart,
ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(10, "bold", Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'center';
this.data.datasets.forEach(function(dataset, i) {
var meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function(bar, index) {
//var data = dataset.data[index];
var data = dataset.data[index];
console.log(bar);
if (data > 0) {
ctx.fillText(data, bar._model.x, bar._model.base - (bar._model.base - bar._model.y) / 2 - 5);
}
});
});
}
}
}
});
I was able to get a working chart by removing the min and max values set.
Here is the JSFiddle
Was the following image the desired outcome?

Categories