How to center bars on x-axis of Chart.js bar graph? - chart.js

I have a really simple Chart.js bar graph where I'm not labeling the x-axis. It looks something like this:
I want my bars to be centered along the x-axis instead of left-aligned as is shown in the pic above. Any ideas? Here's what my data looks like:
datasets: [{
label: 'Blueberries',
data: [this.get('fruit').bluebs[0]],
borderColor: 'blue',
fill: false,
lineTension: 0,
borderDash: [10,5]
}, {
label: 'Apples',
data: [this.get('fruit').apples[1]],
borderColor: 'red',
fill: false,
lineTension: 0.1
}]
And here is my config:
return {
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [{
display: false,
ticks: {
scaleBeginAtZero: false
}
}],
yAxes: [{
display: true,
ticks: {
beginAtZero: true,
fontSize: 12,
fontFamily: 'Lato, sans-serif'
},
scaleLabel: {
display: true,
labelString: 'Fruits Counted',
fontStyle: 'bold',
fontFamily: 'Lato, sans-serif'
}
}]
},
legend: {
display: true,
position: 'bottom',
labels: {
fontColor: '#333',
fontFamily: 'Lato, sans-serif',
}
}
};
Also would love it if the person who downvoted me would tell me why so I can actually take action on it. :/

The default behavior of chart.js is to center charts, Looking at the picture I am doubting that you have supplied two values in the labels array of data (Not sure) if that's not the case please see this fiddle (http://jsfiddle.net/m5rq6bdj/2/) or the below code, which may help.
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
datasets: [{
label: 'Blueberries',
data: [2],
borderColor: 'blue',
fill: false,
lineTension: 0,
borderDash: [10,5]
}, {
label: 'Apples',
data: [1],
borderColor: 'red',
fill: false,
lineTension: 0.1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
xAxes: [{
display: false,
ticks: {
scaleBeginAtZero: false
}
}],
yAxes: [{
display: true,
ticks: {
beginAtZero: true,
fontSize: 12,
fontFamily: 'Lato, sans-serif'
},
scaleLabel: {
display: true,
labelString: 'Fruits Counted',
fontStyle: 'bold',
fontFamily: 'Lato, sans-serif'
}
}]
},
legend: {
display: true,
position: 'bottom',
labels: {
fontColor: '#333',
fontFamily: 'Lato, sans-serif',
}
}
}
});

Related

How to make labels on both side from horizontal bar chart js

I want to make side labels for double horizontal bar on both side like this: pic 1, pic 2
can someone help me idk how to do it, im new in react and chartjs
this post continued from: How to make multiple horizontal bar chartjs
here's what i code:
this the data:
data for chart
export const dataPasienKeluarMasuk = {
type: 'bar',
labels: [
[0, 1, 2, 3,4], // expect output 0 - 4
[5, 6, 7, 8, 9], // expect output 5 - 9
[10, 14], // ext..
[15, 19],
[20, 24],
[25, 29],
[30, 34],
],
datasets: [
{
label: 'Pasien Masuk',
xAxisID: 'A',
data: [100, 90, 80, 70, 60],
backgroundColor: 'red',
},
{
label: 'Pasien Keluar',
xAxisID: 'A',
data: [-100, -90, -80, -70, -60],
backgroundColor: 'blue',
},
],
}
this the chart:
multiple y horizontal bar
import { HorizontalBar } from 'react-chartjs-2'
import { dataPasienKeluarMasuk } from ...blabla
<HorizontalBar
data={dataPasienKeluarMasuk}
height={227}
options={{
responsive: true,
title: {
display: true,
text: 'Data Pasien Keluar Masuk',
fontSize: 20,
},
legend: {
display: true,
position: 'bottom',
},
scales: {
xAxes: [
{
stacked: true,
scaleLabel: {
display: true,
labelString: 'Jumlah Pasien (orang)',
},
ticks: {
// Include a dollar sign in the ticks
callback: (value) => Math.abs(value),
},
},
],
yAxes: [
{
stacked: true,
ticks: {
display: true,
reverse: true,
},
},
],
},
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
let ds = data.datasets[tooltipItem.datasetIndex]
return (
ds.label + ': ' + Math.abs(ds.data[tooltipItem.index])
)
},
},
},
}}
/>
You can obtain the desired result by defining a second y-axis as follows:
{
type: 'category',
position: 'right',
offset: true,
ticks: {
reverse: true,
},
gridLines: {
display: false
}
}
Please take a look at your amended and runnable code below:
new Chart(document.getElementById('canvas'), {
type: 'horizontalBar',
data: {
labels: ['0-4', '5-9', '10-14', '15-19', '20+'],
datasets: [{
label: 'Pasien Masuk',
data: [100, 90, 80, 70, 60],
backgroundColor: 'red',
},
{
label: 'Pasien Keluar',
data: [-100, -75, -60, -75, -70],
backgroundColor: 'blue',
},
]
},
options: {
responsive: true,
title: {
display: true,
text: 'Data Pasien Keluar Masuk',
fontSize: 20,
},
legend: {
position: 'bottom',
},
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
let ds = data.datasets[tooltipItem.datasetIndex];
return ds.label + ': ' + Math.abs( ds.data[tooltipItem.index]);
}
}
},
scales: {
xAxes: [{
stacked: true,
ticks: {
callback: value => Math.abs(value)
}
}],
yAxes: [{
stacked: true,
ticks: {
reverse: true,
}
},
{
type: 'category',
position: 'right',
offset: true,
ticks: {
reverse: true,
},
gridLines: {
display: false
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="canvas" height="100"></canvas>

Chart.Js - Hightligh an area in the background

I need to highlight a fixed area of my chart with a different color between the values 0.5 and 1.5.
Currently my chart is as below:
The desired result is something like this:
As you can see in the above image, the intention is to have a fixed bar with a different color, that is always touching the maximum Y value (this chart auto adjusts the maximum Y value considering the plotted values). The idea is to show the red bars that are in or near this region.
Here is the currently config that I have for this chart:
configPotential = {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 0,
borderColor:'#E16972',
fill: true,
backgroundColor: "#E16972",
order: 1
}]
},
options: {
animation: {
duration: false, //remove animation
},
responsive: true,
tooltips: {
enabled: false
},
title: {
display: false
},
legend: {
display: false
},
elements: {
point:{
radius: 0
}
},
scales: {
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'PSD (Hz/s²)'
},
ticks: {
beginAtZero: true,
suggestedMax: 0.2
}
}],
xAxes: [{
display: false,
},
{
gridLines : {
display : false
},
scaleLabel: {
display: false
},
type: 'linear',
ticks: {
beginAtZero: true,
autoSkip: false,
min: 0,
max: 0.5,
stepSize: 0.1,
}
}]
}
}
}
Resolved using the plugin Chart.Js Annotation - enter link description here
config = {
type: 'bar',
data: {
labels: [],
datasets: [{
data: [],
borderWidth: 0,
borderColor:'#E16972',
fill: true,
backgroundColor: "#E16972",
order: 1
}]
},
options: {
animation: {
duration: false, //remove animation
},
responsive: true,
tooltips: {
enabled: false
},
title: {
display: false
},
legend: {
display: false
},
elements: {
point:{
radius: 0
}
},
scales: {
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'PSD (Hz/s²)'
},
ticks: {
beginAtZero: true,
suggestedMax: 0.2
}
}],
xAxes: [{
display: false,
},
{
gridLines : {
display : false
},
scaleLabel: {
display: false
},
type: 'linear',
ticks: {
beginAtZero: true,
autoSkip: false,
min: 0,
max: 0.5,
stepSize: 0.1,
}
}]
},
annotation: {
drawTime: 'beforeDatasetsDraw',
annotations: [{
type: 'box',
xScaleID: 'x-axis-1',
yScaleID: 'y-axis-1',
xMin: 0.5,
xMax: 0.15,
yMin: 0,
backgroundColor: 'rgba(195,207,221, 0.5)',
borderColor: 'rgba(195,207,221, 0.5)',
}]
}
}
}

How to display axis borders only (no grid lines) in chartjs?

So I only want to show the axes border lines - and hide the grid lines. This is using the latest version of the chart.js package (2.9.3) and I have replicated my issue in a simplified Codepen shown below:
var myChart = new Chart(ctx, {
type: 'scatter',
data: {
labels: [4, 0],
datasets: [{
data: [
{ group_name: "Group A", x: 4, y: 25 },
{ group_name: "Group B", x: 0, y: 0 },
],
}],
},
options: {
legend: { display: false },
scales: {
yAxes: [ {
type: 'logarithmic',
scaleLabel: { display: true, labelString: 'Active %', fontSize: 15 },
position: 'left',
gridLines: { display: false, drawBorder: true },
ticks: {
min: 0,
max: 50,
maxTicksLimit: 4,
padding: 10,
callback: value => `${value.toLocaleString()}%`,
},
} ],
xAxes: [ {
type: 'logarithmic',
position: 'bottom',
scaleLabel: { display: true, labelString: 'User Count', fontSize: 15 },
gridLines: { display: false, drawBorder: true },
ticks: {
min: 0,
maxTicksLimit: 6,
padding: 10,
callback: value => value.toLocaleString(),
},
} ],
},
}
});
Any help or insight is appreciated; the settings I'd expect to work from the docs don't seem to be working.
You can put this options in gridline properties:
xAxes: [{
gridLines: {
display: true,
drawBorder: true,
drawOnChartArea: false
}
}]
Source: https://www.chartjs.org/samples/latest/scales/gridlines-display.html
Solved it (sort of). When I downgrade to chart.js 2.8.0 the chart borders now display as expected. With 2.9.3 the borders were not showing at all, regardless of chart type.
gridLines: { drawBorder: true, lineWidth: 0 }

Chartjs: Overlapping values when using Datalabels plugin

I am using the datalabels plugin, and the values overlap if they are too long:
I tried using the diaply auto under plugins datalabels, but it stills overlaps, any ideas what to do so that they dont overlap?
here are my options:
const getOptions = (yAxisDisplayLabel, data, previousOpts, isMobile) => ({
...previousOpts,
layout: {
padding: {
top: 20,
},
},
plugins: {
datalabels: {
font: {
size: isMobile ? 8 : 12,
},
offset: isMobile ? -15 : -20,
anchor: 'end',
formatter: (value, context) => data.datasets[context.datasetIndex].displayValue[context.dataIndex],
display: 'auto',
align: 'start',
},
},
scales: {
yAxes: [{
ticks: {
display: true,
fontColor: '#c8c8c8',
fontSize: isMobile ? 8 : 12,
fontFamily: 'Futura Book',
beginAtZero: true,
},
gridLines: {
drawBorder: false,
},
scaleLabel: {
display: true,
labelString: yAxisDisplayLabel,
},
}],
xAxes: [{
categoryPercentage: isMobile ? 0.8 : 0.7,
barPercentage: 1,
gridLines: {
display: false,
drawBorder: false,
},
}],
},
legend: {
display: false,
},
scaleBeginAtZero: true,
});
The simple, non-technical, answer is of course to write Unit: €/m2 somewhere else on the chart and not an every bar.

Chartjs mixed bar/line chart bars widths overlaps other columns

I have date chart with a line and a bar datasets.
The problem that I have is that the bar widths is overlapping other columns as the bar dataset will be normally zero.
You can see that the two bars are overlapping with June 4 column.
If I add a bar value in two consecutives days, it will adjust correctly the bar width.
Now the bar widths adjusts for each day column.
If there are more days the bars widths get worst:
You can see that in this chart, it seems that the bars widths overlaps with 4 days in the x axys.
You can check an example code here: https://codepen.io/anon/pen/eKdjay?editors=1010
Uncomment the js code at line 38 to see how the bars width adjusts.
This is the code I use to initialize the chart.
new Chart($('#chart'), {
type: 'bar',
data: {
labels: [],
datasets: [
{
label: "Reach",
data: reachData,
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgb(255, 99, 132)',
borderWidth: 3,
fill: false,
lineTension: 0,
yAxisID: 'y-axis-right',
type: 'line'
}, {
label: "Interactions",
data: interactionsData,
borderColor: 'rgb(139, 195, 74)',
backgroundColor: 'rgb(139, 195, 74)',
borderWidth: 3,
fill: false,
xAxisId: 'x-axis',
lineTension: 0
}
]
},
options: {
bezierCurve : false,
tooltips: {
position: 'nearest',
mode: 'index',
intersect: false,
},
scales: {
xAxes: [{
type: 'time',
time: {
format: 'MM/DD/YYYY',
unit: 'day',
tooltipFormat: 'll'
},
scaleLabel: {
display: true,
labelString: 'Date'
}
}],
yAxes: [{
type: 'linear',
display: true,
position: 'left',
id: 'y-axis-left',
ticks: {
beginAtZero: true
},
scaleLabel: {
display: true,
labelString: "Reach",
fontColor: 'rgb(54, 162, 235)'
}
}, {
type: 'linear',
display: true,
position: 'right',
id: 'y-axis-right',
ticks: {
beginAtZero: true,
},
gridLines: {
drawOnChartArea: false,
},
scaleLabel: {
display: true,
labelString: "Interactions",
fontColor: 'rgb(255, 99, 132)'
}
}]
}
}
});