ChartJS Bar Issue - Showing "zeros" and not center bars - javascript

Im having some trouble with ChartJs and hope you can help. I would like to create a Bar Chart where:
Zero Lables that only contains dataset with zeros are not showing
If only one data value in a chart it is cen
I have added the code example here at codepen: Link to ChartJs CodePen
var Canvas = document.getElementById("myChart");
var Data1 = {
label: 'Project A',
data: [10, 0, 10, 0 ,0 ,0 ,10],
backgroundColor: 'rgba(0, 99, 132, 0.6)',
borderWidth: 0,
yAxisID: "y-axis"
};
var Data2 = {
label: 'Project B',
data: [0 , 5, 5, 0 ,0 ,0 ,10],
backgroundColor: 'rgba(99, 132, 0, 0.6)',
borderWidth: 0,
yAxisID: "y-axis"
};
var MonthData = {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"],
datasets: [Data1, Data2]
};
var chartOptions = {
scales: {
xAxes: [{
barPercentage: 1,
categoryPercentage: 0.6
}],
yAxes: [{
id: "y-axis"
}]
}
};
var barChart = new Chart(Canvas, {
type: 'bar',
data: MonthData,
options: chartOptions
});
Another example, please see below. I have added a link to the source. If i could add data to a Bar Chart the same way it would be perfect.
Link to source of picture
EDIT:
Added a codepen for DX chart: DX Link
/Thomas

ChartJS and the DevExtreme chart are 2 different things. If you want the functionality of dxChart in chartJs then you would have to write it yourself (if you don't have access to the source code to see how they did it).
Helping you with the first point is easy - simply unset the data you don't want. Check here. Don't forget to remove the label you don't want to show.
for (let i = 0; i <= Data1.data.length; i++){
if (Data1.data[i] === 0 && Data2.data[i] === 0) {
Data2.data.splice(i, 1);
Data1.data.splice(i, 1);
labels.splice(i, 1); // also remove the corresponding label
i--; // important not to skip any records after removing
}
}
However this sort of data manipulation I would recommend doing in the back end. Just don't set it before sending to the front end and you're done.
For your second point it looks like chartJs cannot help. There is a reason why dxChart is paid and chartJs is free. Learn to make compromises or become a JS ninja. Cheers

Changing intersect to false for the tooltips should fix the problem. (Intersect: true only shows the tooltips if you're hovering over a datapoint, of which there are none if it's zero)
tooltips configuration can be found here: https://www.chartjs.org/docs/2.6.0/configuration/tooltip.html
var chartOptions = {
scales: {
xAxes: [{
barPercentage: 1,
categoryPercentage: 0.6
}],
yAxes: [{
id: "y-axis"
}]
},
tooltips: {
intersect: false
}
};

Related

Charts.js - How to create a custom X axis

I'm trying to create a mix chart, a bar chart with a line chart. Below is a picture of a standard example.
I need to change the x-axis as shown in the picture below, how can I do that?
In other words, I want to remove the dependence of x-axis labels on the number of bars and their points and make the x-axis arbitrary, which sets the maximum and minimum values and its step
Change the labels as shown in this example:
const data = {
// Put whatever you want
labels: [0, 5, 10, 15, 20],
datasets: [
{
/* ........ */
},
]
};
I found a solution, we need to add a new dataset and bind it to a custom X axis.
datasets: [{
type: chartTypes.Line,
xAxisID: 'custom-X-axis',
},
/*...*/]
Then we need to add this custom axis and hide the default one
scales: {
xAxes: [
{
display: false,
}, {
id: 'custom-X-axis',
type: 'linear',
ticks: {
min: 0,
max: 20,
}
}
],
}

Bars centered between the grid lines with the label below the grid lines (chart.js)

I want to create a bar chart where the bars are centered between the grid lines.
This behaviour was possible before this merge request:
https://github.com/chartjs/Chart.js/pull/4545
In the original version this was possible with offsetGridLines: false (category scale).
I created a stackblitz with a angular app using chart.js and ng2-charts:
https://stackblitz.com/edit/angular-barchart-example-mg192a?file=src%2Fapp%2Fbarchart%2Fbarchart.ts
Working Code with chart.js 2.6.0:
public barChartOptions:any = {
scaleShowVerticalLines: false,
responsive: true,
scales: {
xAxes: [{
offset: true,
gridLines: {
offsetGridLines: false
}
}]
}
}
Results in a bar chart like I want it to be (only the bars could still be centered between the grid lines):
In the current version of Chart.js (I'm currently using 2.9.3) the bars are arranged to the right and left of the grid lines:
Does the new version of chart.js offer the possibility to center the bars between the gridlines?
First you need to define categoryPercentage: 1 for both datasets.
public barChartData:any[] = [
{
data: [55, 60, 75, 82, 56, 62, 80],
label: 'Company A',
categoryPercentage: 1,
},
{ data: [58, 55, 60, 79, 66, 57, 90],
label: 'Company B',
categoryPercentage: 1,
}
];
categoryPercentage (default 0.8): Percent (0-1) of the available width each category should be within the sample width. more...
Chart.js however still won't properly layout the bars if some of them are not contained in the visible area. Therefore you'll also have to make sure that all bars are shown in the chart by defining an appropriate value for yAxis.ticks.min.
yAxes: [{
ticks: {
min: 50
}
}]
Please have a look at your amended code in the following StackBlitz

Plot Ranged horizontal bar graph with holes using ChartJS

I already have a graph using chartJS as shown below and the code for that is :
r_chart_data = [[-0.001, 2.052],[-2.385, 2.052]];
dr_chart_data = [[-0.01, 1.83],[1.05, 2.83],[1.05, 2.83]];
myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: label,
datasets: [{
label : 'DataSet1',
data: r_chart_data,
backgroundColor: 'rgb(255, 99, 132)'
},
{
label : 'DataSet2',
data: dr_chart_data,
backgroundColor: 'lightblue'
}
]
},
options: {
lineAtIndex : level,
scales: {
xAxes: [{
ticks: {
min: -5,
max: 5,
stepSize: 0.5,
}
}]
}
}
});
But what if my
r_chart_data[0] i.e. [-0.001,2.052]
is not a continuos range and instead its value is something like
[[-0.001,1.023],[1.5,2.052]]
then how should I plot the graph. Modified r_chart_data:
r_chart_data = [[[-0.001,1.023],[1.5,2.052]],[-2.385, 2.052]];
Similarly if I have a range of data sets that I need to plot in the form of a horizontal bar graph using ChartJS. The data set which are in the form of:
dataset1: [[-10,-4],[-2,2],[4,6]] // should be plotted in a single bar graph
dataset2: [[-2,1],[1.5,3.5],[5.2,8.9]] //should be plotted in a second bar
dataset3: [[2,4],[5,7]] //third bar
.. and so on
Moreover, each dataset need not have three range items. It can have one, two or any number of range items.

How to expand the slice of donut chart in chartjs?

Is there any way to expand the slice of donut chart onclick event or mouse hover in chartjs ?.
I am using chart.js#2.8.0 version.
I have fixed this issue using the following code:
let segment;
this.chart = new Chart(this.canvas, {
type: this.type,
data: this.data,
options: {
...this.options,
onHover: function (evt, elements) {
if (elements && elements.length) {
segment = elements[0];
this.chart.update();
selectedIndex = segment["_index"];
segment._model.outerRadius += 10;
} else {
if (segment) {
segment._model.outerRadius -= 10;
}
segment = null;
}
},
layout: {
padding: 30
}
}
});
I hope it helps you.
Shift-zooming the currently selected slice is not a feature but it has been discussed several times on various forums and the project's GitHub community:
https://forum.mendixcloud.com/link/questions/85582
https://github.com/chartjs/Chart.js/issues/1451
The Github discussion contains a fiddle someone wrote for a Pie chart with Chart.js 1.0. Here is an updated version for the current Chart.js version that supports Donut charts.
Code:
This part only shows the part that zooms the active element, it is just to give you the idea of how to use the active elements .innerRadius and .outerRadius properties to shift the element. The fiddle contains the complete code that also handles shrinking the previously selected element.
<div style="width:400px;">
<canvas id="myChart" width="200" height="200"></canvas>
</div>
var ctx = document.getElementById('myChart');
var myChart = new Chart(ctx, {
type: 'doughnut',
options: {
layout: {
padding: 30
}
},
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [
{
label: '# of Votes',
data: [4, 5, 3],
backgroundColor: [
'rgba(255, 0, 0, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
],
borderWidth: 3
}]
}
});
var addRadiusMargin = 10;
$('#myChart').on('click', function(event) {
var activePoints = myChart.getElementsAtEvent(event);
if (activePoints.length > 0) {
// update the newly selected piece
activePoints[0]['_model'].innerRadius = activePoints[0]['_model'].innerRadius +
addRadiusMargin;
activePoints[0]['_model'].outerRadius = activePoints[0]['_model'].outerRadius +
addRadiusMargin;
}
myChart.render(300, false);
}
Sample image:
Here is a sample of the highlighted slice:
Limitations:
There are two limitations of the sample that I haven't included:
Chart.js does not allow to define a margin between legend and chart content so when you are "zooming"/"moving", the zoomed slice might overlap parts of the legend. You may solve this by extending the legend as shown in Jordan Willis' Codepen which was the result of this SO question.
The selected slice will stay in contact with the remaining slices. If you want it to have a gap, you need to translate x and y of the active slice based on the .startAngle and .endAngleproperties of the active slice.
Another simple trick : hoverBorderWidth
var ctx = document.getElementById("chart").getContext('2d');
var chart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Microsoft Internet Explorer", "Google Chrome", "Mozilla Firefox", "Opera", "Safari"],
datasets: [{
label: 'Number of votes',
data: [60, 20, 10, 8, 5],
backgroundColor: ['#96ceff', '#424348', '#91ee7c', '#f7a35b', '#8286e9'],
borderColor: '#fff',
borderWidth: 1,
hoverBorderColor: ['#96ceff', '#424348', '#91ee7c', '#f7a35b', '#8286e9'],
hoverBorderWidth: 8
}]
},
options: {
responsive: false,
legend: {
display: false
},
tooltips: {
displayColors: false
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<canvas id="chart" width="350" height="350"></canvas>

Cannot change chart.js color fill or y axes

I am trying to make a real time graph using chart.js, but I cannot seem to change the color fills.
<script type="text/javascript">
var canvas = document.getElementById('updating-chart'),
ctx = canvas.getContext('2d'),
startingData = {
labels: ["A", "B", "C", "D"],
datasets: [
{
label: "Product A",
fillColor: "rgba(206, 70, 90, 1)",
strokeColor: "rgba(220,220,220,0.8)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
data: [65, 59, 80, 81],
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true,
min: 0,
max: 10
}
}]
}
}
}
]
};
var myLiveChart = new Chart(ctx,{
type: 'bar',
data: startingData,
responsive: true,
maintainAspectRatio: true
});
setInterval(function(){
// Get a random index point
var indexToUpdate = Math.round(Math.random() * startingData.labels.length);
// Update one of the points in the second dataset
myLiveChart.data.datasets[0].data[indexToUpdate] = Math.random() * 100;
myLiveChart.update();
}, 500);
</script>
I've clearly changed the axes and set the y to a maximum, but it still overflows and keeps dynamically changing the axes length. How do I fix this?
Also the color still seems to be grey for the first bar, even though I changed the rgba values. Help?
refer the below link for changing the colors.try background-color.If you share the fiddle it will help.
http://www.chartjs.org/docs/#chart-configuration-colors
Add below code in your datasets array. Color will change.
backgroundColor:"rgba(206, 70, 90, 1)"
https://jsfiddle.net/Smita31Jain/4zpuxvke/
For overflow and dynamically changing axes length issue, take out options property object code from startingData object's dataset array and add it to myLiveChart chart instance. Refer below jsfiddle
https://jsfiddle.net/Smita31Jain/zzpkxg3k/
Hope this is what you are looking for.

Categories

Resources