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

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,
},
},
}}
/>

Related

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">

Fill empty space in line Apache ECharts

is possible in apache echarts to fill space from left and right?
When i'm use boundaryGap: false it looks like that (first and last value are partially hidden):
i need to fill left and right empty spaces and i have no idea how... Thanks
heres my code:
option = {
xAxis: {
type: 'category',
boundaryGap: false,
data: ['a', 'b','c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l'],
axisTick: {
show: false,
},
axisLine: {
show:false,
},
},
grid:{
height: 200,
left: 0,
right: 0,
},
yAxis: {
min: -10,
type: 'value',
silent: false,
axisLine:false,
axisLabel: false,
axisTick: false,
minorSplitLine: {
show: false
},
splitLine: {
show: true,
lineStyle: {
color: "#EAEEF6",
opacity: "1",
width: "1",
},
}
},
series: [
{
label: {
normal: {
show: true,
position: 'top',
color: '#474646',
fontSize:12,
fontWeight: 'bold'
}
},
data: [2,1,-4,-4,-3,-3,-5,-4,0,1,1.5,2],
type: 'line',
smooth: true,
}
],
}
https://jsfiddle.net/zm8whknr/
Option 1: You can modify the grid.left and grid.right options to set the left and right spacing of the chart to accommodate the cropped values,
grid:{
height: 200,
left: 10,
right: 10,
},
Result:
Option 2: You can align the first and last element's xaxis label and data label to 'left' and 'right' to avoid cropping.
Modified xAxis option,
xAxis.data = [{value:'a', textStyle:{'align': 'left'}}, ... ,{value:'l', textStyle:{'align': 'right'}}],
Modified Series data option,
series[0].data = [{value:2, label:{'align': 'left'}}, ... , {value:2, label:{'align': 'right'}}],
Chart Option,
option = {
xAxis: {
type: 'category',
boundaryGap: false,
data: [{value:'a', textStyle:{'align': 'left'}},'b','c','d','e','f','g','h','i','j','k',{value:'l', textStyle:{'align': 'right'}}],
axisTick: {
show: false,
},
axisLine: {
show:false,
},
},
grid:{
height: 200,
left: 0,
right: 0,
},
yAxis: {
min: -10,
type: 'value',
silent: false,
axisLine:false,
axisLabel: false,
axisTick: false,
minorSplitLine: {
show: false
},
splitLine: {
show: true,
lineStyle: {
color: "#EAEEF6",
opacity: "1",
width: "1",
},
}
},
series: [
{
label: {
normal: {
show: true,
position: 'top',
color: '#474646',
fontSize:12,
fontWeight: 'bold'
}
},
data: [{value:2, label:{'align': 'left'}},1,-4,-4,-3,-3,-5,-4,0,1,1.5, {value:2, label:{'align': 'right'}}],
type: 'line',
smooth: true,
animationDelay: idx => idx * 100,
lineStyle: {
normal: {
width: 4,
color:'#29d9c9',
shadowColor: 'rgba(41, 217, 201, 0.5)',
shadowOffsetX: 0,
shadowOffsetY: 8,
shadowBlur: 10
},
},
areaStyle: {
origin: 'start',
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 0,
color: 'rgba(0, 214, 143, 0.3)',
}, {
offset: 1,
color: 'rgba(0, 214, 143, 0)',
}]),
opacity: 1,
},
itemStyle:{
color: '#29d9c9',
borderWidth: 5
},
symbolSize: 5
}
],
animationEasing: 'elasticOut',
animationDelayUpdate: idx => idx * 5,
}

Zoom-In functionality in histogram using Chart.js

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; } } } } ]
}
}
};

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
}
}
}
});

How to make a square and horizontal lines in highcharts?

Need help with highchartsJs. I need chart like on screenshots. For lines i found this, but not fully what i needed. For square i don't have any ideas. Square is most priority.
Any help will be appreciated. Thanks.
square
horizontal lines
If someone need something like this
https://jsfiddle.net/gdgb941o/20/
chart: {
type: 'column'
},
title: {
text: false
},
tooltip: {
enabled: false
},
credits: {
enabled: false
},
xAxis: {
tickWidth: 0,
lineWidth: 0,
type: 'category',
gridLineWidth: 0
},
yAxis: {
lineWidth: 0,
gridLineWidth: 0,
labels: {
enabled: false
},
max: 100,
title: {
text: false
}
},
navigation: {
buttonOptions: {
enabled: false
}
},
legend: {
enabled: false
},
plotOptions: {
column: {
borderWidth: 0,
grouping: false
},
series: {
}
},
series: [{
data: [{
borderWidth: 2,
borderColor:'#41bc9b',
color: 'white',
name: 'Yes',
y: 100,
dataLabels: {
formatter: function() {
return "33" + "%"
},
enabled: true,
inside: true,
align: 'center',
color: 'black',
style: {
fontSize: 20,
textOutline: false
}
}
}, {
borderWidth: 2,
borderColor:'#41bc9b',
color: 'white',
name: 'The email did not come',
y: 100,
dataLabels: {
formatter: function() {
return "80" + "%"
},
enabled: true,
inside: true,
align: 'center',
color: 'black',
style: {
fontSize: 20,
textOutline: false
}
}
}, {
borderWidth: 2,
borderColor:'#41bc9b',
color: 'white',
name: 'Error in verification',
y: 100,
dataLabels: {
formatter: function() {
return "55" + "%"
},
enabled: true,
inside: true,
align: 'center',
color: 'black',
style: {
fontSize: 20,
textOutline: false
}
}
},
{
borderWidth: 2,
borderColor:'#41bc9b',
color: 'white',
name: 'No',
y: 100,
dataLabels: {
formatter: function() {
return "20" + "%"
},
enabled: true,
inside: true,
align: 'center',
color: 'black',
style: {
fontSize: 20,
textOutline: false
}
}
}]
}, {
pointPadding: 0.125,
data: [{
color: '#41bc9b',
name: 'Yes',
y: 33
}, {
color: '#41bc9b',
name: 'The email did not come',
y: 80
}, {
color: '#41bc9b',
name: 'Error in verification',
y: 55
},
{
color: '#41bc9b',
name: 'No',
y: 20
}]
}]

Categories

Resources