Zoom-In functionality in histogram using Chart.js - javascript

I have a created a histogram using chart.js. (Referring Make a Histogram in Chart.js). Now i need a zoom in functionality because by default if i am enabling zoom in chart labels and bars are not in-sync. And my data is too much in chart. so i need with width of bar.
This is my config object.
const config: any = {
type: 'bar',
data: {
labels: xLabelx,
datasets: [ { label: 'Count', backgroundColor: 'rgba(215, 239, 252,0.5)', data: NumberOfVehicle,
borderColor: '#37B1F0', borderWidth: 0.5, hoverBackgroundColor: '#66bcff' } ]
},
options: {
tooltips: {
mode: 'label',
bodyFontSize: 12,
opacity: 0.5,
borderWidth: 5,
callbacks: {
title: (tooltipItems, data) => { return ''; },
label(tooltipItem, data) {
const label = data.datasets[tooltipItem.datasetIndex].label;
const value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return label + ': ' + value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '');
} } },
pan: { enabled: true, mode: 'xy', drag: true, speed: 10, threshold: 10 },
zoom: { enabled: true, drag: false, mode: 'x' },
maintainAspectRatio: false,
responsive: false,
legend: {
display: true,
onHover: (event, legendItem) => { document.getElementById('myChart').style.cursor = 'pointer'; },
labels: { fontSize: 14 }},
hover: {
onHover: (e, el) => { $('#myChart').css('cursor', el[0] ? 'pointer' : 'default'); }
},
scales: {
xAxes: [
{ display: false, barPercentage: 1.25, ticks: { max: xLabelx[xLabelx.length - 2] }},
{ display: false, ticks: { autoSkip: false, max: xLabelx[xLabelx.length - 1]}},
{ scaleLabel: { display: true, labelString: 'Range', fontFamily: 'Roboto', fontSize: 14 }}
],
yAxes: [
{ scaleLabel: { display: true, labelString: 'No. of model', fontFamily: 'Roboto', fontSize: 14 },
ticks: { beginAtZero: true, fontSize: 12, userCallback: (label, index, labels) => {
if (Math.floor(label) === label && label >= 0) { return label; } } } } ]
}
}
};

Related

How can I start Chartjs bars from left side instead of center?

I created a bar chart using ChartJS. The problem is when a data point is small like 2 length. It align all bars in center.
But I don't want this.
The canvas width is 100% to its wrapper. Bars thickness max 14.Below is my code summary. Please help.
The output is like that but i want to both of them bars align to left.
const dataSet = {
type: 'bar',
labels: labels,
datasets:
data.dataSets.length === 1
? [
{
data: data.dataSets[0].data,
backgroundColor: data.dataSets[0].color,
borderRadius: 20,
borderWidth: 0,
barPercentage: 0.4,
maxBarThickness: 14,
hoverBorderWidth: 1,
hoverBackgroundColor: data.dataSets[0].color,
},
{
xAxisID: 'axisX2',
yAxisID: 'axisY2',
label: ' ',
backgroundColor: '#4C4E6414',
hoverBackgroundColor: '#4C4E6414',
hoverBorderWidth: 0,
borderWidth: 0,
barPercentage: 0.4,
maxBarThickness: 14,
borderRadius: 20,
data: data.dataSets[0].data.map((item: any) => 1000),
},
]
: data.dataSets.map((item: any) => {
return {
data: item.data,
backgroundColor: item.color,
borderRadius: 20,
borderWidth: 0,
barPercentage: 0.4,
maxBarThickness: 14,
hoverBorderWidth: 1,
hoverBackgroundColor: item.color,
};
}),
};
<Bar
id="bar-chart"
data={dataSet}
options={{
responsive: true,
maintainAspectRatio: false,
interaction: {
mode: 'nearest',
axis: 'x',
intersect: false,
},
plugins: {
legend: {
display: false,
},
tooltip: {
enabled: true,
backgroundColor: '#F7F7F9',
titleColor: 'rgba(76, 78, 100, 0.3)',
titleFont: {
size: 13,
},
bodyColor: 'rgba(76, 78, 100, 0.5)',
filter: function (tooltipItem) {
return data.dataSets.length === 1 ? tooltipItem.datasetIndex !== 1 : true;
},
displayColors: data.dataSets.length === 1 ? false : true,
callbacks: {
label: function (tooltipItem) {
return data.dataSets[tooltipItem.datasetIndex]?.label + ' ' + currency + tooltipItem.formattedValue;
},
labelColor: function (tooltipItem) {
return {
borderColor: 'transparent',
backgroundColor: data.dataSets[tooltipItem.datasetIndex]?.color,
borderWidth: 2,
borderRadius: 5,
};
},
},
},
},
scales: {
x: {
axis: 'x',
beginAtZero: true,
border: {
display: false,
},
grid: {
display: false,
drawTicks: false,
},
ticks: {
display: false,
},
},
y: {
axis: 'y',
beginAtZero: true,
border: {
display: false,
},
grid: {
drawTicks: false,
display: false,
},
ticks: {
display: false,
padding: 0,
mirror: true,
},
},
axisX2: {
axis: 'x',
position: 'left',
beginAtZero: true,
border: {
display: false,
},
grid: {
display: false,
drawTicks: false,
},
ticks: {
display: false,
},
},
axisY2: {
axis: 'y',
position: 'left',
beginAtZero: true,
border: {
display: false,
},
grid: {
drawTicks: false,
display: false,
},
ticks: {
padding: 0,
display: false,
mirror: true,
},
},
},
layout: {
padding: {
left: 0,
right: 0,
top: 0,
bottom: 0,
},
},
}}
/>

chart js 3.9.1 - barchart - margin left

how do i reduce the space between the bar and the y scale? I tried with padding but it doesn't work
Thanks
This is my configuration,I upload the data at runtime and update the graph
Chart.register(ChartDataLabels);
var options = {
tooltips: {
enabled: false
},
plugins:
{
datalabels:
{
color: 'white'
},
legend: {
position: 'top', labels:
{
font: {size: 10},
usePointStyle: true
}
}
},
scales:
{
x: {
barPercentage: 6.5,
categoryPercentage: 0.1
},
y: {
barPercentage: 1,
categoryPercentage: 1,
beginAtZero: true,
grace: '3%',
ticks: {
beginAtZero: true
}
}
}
};
var barChart = new Chart(document.getElementById("chart3"), {
type: 'bar',
data:
{
labels: [""]
},
options:options
});
for (i = 0; i < parsed[0].length; i++)
{
barChart.data.datasets.push({ label: parsed[0][i].label, backgroundColor: parsed[0][i].backgroundColor, data: ["" + parsed[0][i].data + ""], pointStyle:'circle' });
}
barChart.update();
The issue sounds being related to categoryPercentage and barPercentage options that you are set in the axis but this is not the right place.
Move those options in the chart.options and it should work.
Try using categoryPercentage: 1.
var options = {
categoryPercentage: 1,
plugins:
{
datalabels:
{
color: 'white'
},
legend: {
position: 'top', labels:
{
font: {size: 10},
usePointStyle: true
}
}
tooltip: {
enabled: false
},
},
scales:
{
y: {
beginAtZero: true,
grace: '3%',
}
}
};

How can I change background color of a specific area in my chart's grid using Chart.js and Annotation?

I'm having some trouble trying to change the backgroundColor of a specific chart area between two yAxis ticks.This is what I have so far:
And this is what I wanted:
I've seen some similar posts about that and people recommend using Annotation to do this. I tried using it on my chart and it didn't work. This is my first time building a chart with chart.js so I'm still learning. Here's my code:
var profileChart = new Chart(ctx1, {
type: "line",
data: {
labels: ["", "D", "I", "S", "C", ""],
datasets:[{
data: [],
borderWidth: 1,
pointBackgroundColor: "black",
backgroundColor: "black",
borderColor: "black",
fill: false,
lineTension: 0,
yAxisID: 'first-y-axis'
},
{
yAxisID: 'third-y-axis'
}],
},
options: {
title: {
display: true,
text: 'Gráfico do Perfil DISC',
fontSize: 20,
},
scales: {
yAxes: [{
id: 'first-y-axis',
type: 'linear',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
padding: '15px',
labelString: 'Intensity'
},
ticks: {
max: 28,
min: 1,
stepSize: 1
}
},
{
id: 'second-y-axis',
type: 'linear',
position: 'left',
gridLines: {
drawOnChartArea: true
},
ticks: {
display: false,
min: 1,
max: 8,
stepSize: 1
}
},
{
id: 'third-y-axis',
position: 'right',
type: 'linear',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
padding: '10px',
labelString: 'Segment'
},
ticks: {
max: 7.5,
min: 0.5,
stepSize: 1
},
afterTickToLabelConversion: function(scaleInstance) {
scaleInstance.ticks[0] = null;
scaleInstance.ticks[scaleInstance.ticks.length - 1] = null;
scaleInstance.ticksAsNumbers[0] = null;
scaleInstance.ticksAsNumbers[scaleInstance.ticksAsNumbers.length - 1] = null;
},
}]
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return tooltipItem.yLabel;
}
}
}
},
annotation: {
drawTime: "afterDraw",
annotations: [{
id: 'box1',
type: 'box',
yScaleID: 'second-y-axis',
yMin: 12.5,
yMax: 16.5,
backgroundColor: 'grey',
}]
}
});
You can draw the rectangle directly on the canvas using the Plugin Core API. The API offers a range of hooks that may be used for performing custom code.
In your amended code below, I use the beforeDraw hook to draw the rectangle through CanvasRenderingContext2D.fillRect().
var profileChart = new Chart('canvas', {
type: "line",
plugins: [{
beforeDraw: chart => {
var ctx = chart.chart.ctx;
var xAxis = chart.scales['x-axis-0'];
var yAxis = chart.scales['first-y-axis'];
ctx.save();
ctx.fillStyle = 'lightgray';
ctx.beginPath();
var yTop = yAxis.getPixelForValue(16.5);
var yBottom = yAxis.getPixelForValue(12.5);
ctx.fillRect(xAxis.left, yTop, xAxis.right - xAxis.left, yBottom - yTop);
ctx.stroke();
ctx.restore();
}
}],
data: {
labels: ["", "D", "I", "S", "C", ""],
datasets: [{
data: [,25.5, 8, 7.5, 11],
borderWidth: 1,
pointBackgroundColor: "black",
backgroundColor: "black",
borderColor: "black",
fill: false,
lineTension: 0,
yAxisID: 'first-y-axis'
},
{
yAxisID: 'third-y-axis'
}
],
},
options: {
title: {
display: true,
text: 'Gráfico do Perfil DISC',
fontSize: 20,
},
scales: {
yAxes: [{
id: 'first-y-axis',
type: 'linear',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
padding: '15px',
labelString: 'Intensity'
},
ticks: {
max: 28,
min: 1,
stepSize: 1
}
},
{
id: 'second-y-axis',
type: 'linear',
position: 'left',
gridLines: {
drawOnChartArea: true
},
ticks: {
display: false,
min: 1,
max: 8,
stepSize: 1
}
},
{
id: 'third-y-axis',
position: 'right',
type: 'linear',
gridLines: {
drawOnChartArea: false
},
scaleLabel: {
display: true,
padding: '10px',
labelString: 'Segment'
},
ticks: {
max: 7.5,
min: 0.5,
stepSize: 1
},
afterTickToLabelConversion: function(scaleInstance) {
scaleInstance.ticks[0] = null;
scaleInstance.ticks[scaleInstance.ticks.length - 1] = null;
scaleInstance.ticksAsNumbers[0] = null;
scaleInstance.ticksAsNumbers[scaleInstance.ticksAsNumbers.length - 1] = null;
},
}
]
},
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem) {
return tooltipItem.yLabel;
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.min.js"></script>
<canvas id="canvas" height="200">

How to display value after the bar using chart.js

My chart.js
var ctx_1 = document.getElementById('https_http').getContext('2d');
var myChart_1 = new Chart(ctx_1, {
type: 'horizontalBar',
data: {
labels: ['HTTPS Pages','HTTP Pages'],
datasets: [{
data: [ {{ $array_https_http[0] }}, {{ $array_https_http[1] }}],
backgroundColor: [
'rgb(81, 170, 120)',
'rgb(198, 222, 208)'
]
}]
},
options: {
showAllTooltips: true,
tooltips: {
enabled: true,
displayColors: false,
yPadding: 20,
xPadding: 30,
caretSize: 10,
backgroundColor: 'rgba(240, 240, 240, 1)',
bodyFontSize: 16,
bodyFontColor: 'rgb(50, 50, 50)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
cornerRadius: 0,
yAlign: 'bottom',
xAlign: 'center',
position: 'custom',
custom: function(tooltip) {
if (!tooltip) return;
// disable displaying the color box;
tooltip.displayColors = false;
},
callbacks: {
// use label callback to return the desired label
label: function(tooltipItem, data) {
return tooltipItem.yLabel + " : " + tooltipItem.xLabel ;
},
// remove title
title: function(tooltipItem, data) {
return;
}
}
},
responsive: false,
legend: { display: false },
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
},
gridLines: {
display: false
},
}],
xAxes: [{
ticks: {
stepSize:100
}
}],
}
}
});
My tooltips code
Chart.Tooltip.positioners.custom = function(elements, position) {
if (!elements.length)
return false;
var em = elements[0]._model;
return {
x: em.x-((em.x-em.base)/2),
y: em.y+em.height/4
}
}
My output
My expected output
Is there anyone can help me how to put those value after the bar like the second picture. I just want to display the value to know even its zero. My custom tooltips was to show a different hover rather than default. All your help are appreciated and thank you in advance.
You can use the chartjs.datalabel plugin for achieving the need. I have created a fiddle for you -> http://jsfiddle.net/Labkrpf4/
Hope it helps!
var ctx_1 = document.getElementById('https_http').getContext('2d');
var myChart_1 = new Chart(ctx_1, {
type: 'horizontalBar',
data: {
labels: ['HTTPS Pages', 'HTTP Pages'],
datasets: [{
data: [0, 430],
backgroundColor: [
'rgb(81, 170, 120)',
'rgb(198, 222, 208)'
]
}]
},
options: {
showAllTooltips: true,
tooltips: {
enabled: true,
displayColors: false,
yPadding: 20,
xPadding: 30,
caretSize: 10,
backgroundColor: 'rgba(240, 240, 240, 1)',
bodyFontSize: 16,
bodyFontColor: 'rgb(50, 50, 50)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 1,
cornerRadius: 0,
yAlign: 'bottom',
xAlign: 'center',
position: 'custom',
custom: function(tooltip) {
if (!tooltip) return;
// disable displaying the color box;
tooltip.displayColors = false;
},
callbacks: {
// use label callback to return the desired label
label: function(tooltipItem, data) {
return tooltipItem.yLabel + " : " + tooltipItem.xLabel;
},
// remove title
title: function(tooltipItem, data) {
return;
}
}
},
responsive: false,
legend: {
display: false
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
gridLines: {
display: false
},
}],
xAxes: [{
ticks: {
stepSize: 100
}
}],
},
plugins: {
datalabels: {
align: 'end',
anchor: 'end',
backgroundColor: function(context) {
return context.dataset.backgroundColor;
},
borderRadius: 4,
color: 'white',
formatter: Math.round
}
}
}
});

Chart.js add border around line chart, and yAxis unit title ([s])

I have problem with chartJS. I cannot add border around chart, yAxis unit title, and yAxis labelString with element. I'm using react with typescript. I can add only string to labelString. You can see what I want do do on screen and on another screen you can see what I actualy have.
Is there any options in chart.js#2.7.1 to add these elements?
First image is my goal. Second is actual.
#edit
This is my chartOptions file. I just pass arguments in function to get these options.
import * as Chart from 'chart.js';
const getOptions = (
beginAtZero: boolean,
tickMax: number,
tickStepValue: number,
titleText: string,
xAxesLabelString: string,
yAxesLabelString: string,
): Chart.ChartOptions => {
const ticks: Chart.LinearTickOptions = {
beginAtZero,
fontColor: '#3C3750',
fontFamily: 'Muli',
fontSize: 10,
fontStyle: 'bold',
max: tickMax,
stepSize: tickStepValue,
};
const options: Chart.ChartOptions = {
legend: {
display: false,
},
maintainAspectRatio: false,
responsive: true,
scales: {
xAxes: [{
display: true,
gridLines: {
display: false,
},
scaleLabel: {
display: true,
fontColor: '#3C3750',
fontFamily: 'Muli',
fontSize: 10,
fontStyle: 'bold',
labelString: xAxesLabelString,
},
ticks,
}],
yAxes: [{
display: true,
gridLines: {
drawBorder: true,
tickMarkLength: 15,
},
scaleLabel: {
display: true,
fontColor: '#3C3750',
fontFamily: 'Muli',
fontSize: 10,
fontStyle: 'bold',
labelString: yAxesLabelString,
},
ticks,
}],
},
title: {
display: true,
text: titleText,
},
tooltips: {
backgroundColor: '#E4677B',
callbacks: {
label: (tooltipItem, data) => {
return 'Time: ' + data.datasets[0].data[tooltipItem.index];
},
title: (tooltipItem, data) => {
return '';
},
},
custom: (tooltip) => {
if (!tooltip) {
return;
}
// disable displaying the color box;
tooltip.displayColors = false;
},
},
};
return {
...options,
};
};
export default getOptions;
public createChart({room, roomState, chartOptions, chartDataset, chartLabels}: ILineChartProps) {
const ctx = this.canvas.getContext('2d');
this.myChart = new Chart(ctx, {
data: {
datasets: chartDataset,
labels: chartLabels,
},
options: chartOptions,
type: 'line',
});
}
Adding one xAxes on top and one yAxes on right both showing nothing will do the job.
scales: {
xAxes: [{
/* Your xAxes options here */
}, {
position: 'top',
ticks: {
display: false
},
gridLines: {
display: false,
drawTicks: false
}
}],
yAxes: [{
/* Your yAxes options here */
}, {
position: 'right',
ticks: {
display: false
},
gridLines: {
display: false,
drawTicks: false
}
}]
}
This is what worked for me.
scales: {
xAxes: [
{
/* Your xAxes options here */
},
{
position: 'top',
ticks: {
display: false
},
gridLines: {
display: true,
drawOnChartArea: false,
drawTicks: false
}
}
],
yAxes: [
{
/* Your yAxes options here */
},
{
position: 'right',
ticks: {
display: false
},
gridLines: {
display: true,
drawOnChartArea: false,
drawTicks: false
}
}
]
}

Categories

Resources