Chart.js How to align two X-axis in bar chart? - javascript

I try to build a simple bar chart using chart.js with 2 x-axis: One on top and other on bottom.
The problem is two axis label and grid is not align. The top x-axis is align center and bottom x-axis is align left.
Please help me to make two x-axis align center. Thanks!
Fiddle:
jsfiddle.net/gtmvkq4n/2/
Screenshot:

You may be looking after the offset option
Example with multiple datasets:
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['A', 'B', 'C', 'D', 'E'],
datasets: [{
label: 'somelabel',
xAxisID:'bar-x-axis1',
data: [40, 50, 30, 12, 52]
},
{
// ... other dataset...
}]
},
options:{
scales:{
xAxes:[
{
id:'bar-x-axis1',
type:'category',
offset: true // <== that one!
},
{
// ... other X axis...
}]
}
}
});
http://www.chartjs.org/docs/latest/axes/cartesian/

Make your bar graph contains proper groupSpace, barSpace, barWidth
(groupSpace * barSpace) * n + groupSpace = 1
Make this equation is correct, given n is the number of bars

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

How to set custom scale to polar area chart?

The Problem:
I am using polar area chart. For slices in this chart, each value after the largest value should appear one level smaller. The level is as follows: for example, if the value after a 38 slice is 6, it should look like 37. Or I should be able to set it to the level I want. My question is all about sizing the slices on the polar area.
What I get:
What I want:
Sorry for my bad drawing. You can think what i want is like:
scaling very small slices close to large slice.
Methods I tried:
I tried changing the scale and ticks parameters from the link chartjs axes settings but without success.
I put the index data after sorting the array as data into the dataset. It worked as I wanted, but this time the values appeared as index values.
Charts.js polar area scales I tried this also but not worked.
A solution can be reached from the two methods I tried, but I could not.
Code example here:
function SetWorkflowChart(labels, datas, labelColors) {
//label colors
// workflow stats chart
const workflowdata = {
labels: labels,
datasets: [{
normalized: true,
data: datas, // example data: [38, 5,3]
backgroundColor: labelColors,
borderColor: "rgba(0, 0, 0, 0.0)"
}]
};
const workflowconfig = {
type: 'polarArea',
data: workflowdata,
options: {
scales: {
r: {
grid: {
display: false
},
ticks: {
display: false //try2 i tried to set ticks for scale
},
suggestedMin: 5, //try1
suggestedMax: 20,//try1
}
},
plugins: {
legend: {
display: false,
position: "right"
},
},
responsive: false
}
};
workflowChart = new Chart(
document.getElementById('WorkFlowStatsChart'),
workflowconfig
);
}
I'll be pleased if you pay attention.

ChartJS 3 get height of stacked vertical bar

Ok. So I'm trying to use ChartJS with Datalabels 2.0 (RC) to show labels for stacked vertical bars. When the bar is small, I want those labels to appear outside of it.
Now here is the code I'm using: https://codepen.io/meexo/pen/xxqpELL
The problem I have is that using getProps on dataset, I am unable to retrieve the height of each bar. In the example above I tried to get height by using the getProps() introduced in ChartJS 3. If I console.log it, I see all kind of params, height included (though undefined). What am I doing wrong that height parameter is undefined?
I also tried to use getProps().y param for the code, but in that case it seems to apply only to one section of the stacked bar, not all. And what I want is for labels to appear above the stacked bar when the full height if it is lower than my threshold.
Any ideas?
BTW, though its my first question, its definitely not the first answer I found on StackOverflow :)
My code:
var ctx = document.getElementById("myChart");
Chart.register(ChartDataLabels);
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'red'
}, {
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: 'blue'
}]
},
options: {
scales: {
x: {
stacked: true
},
y: {
stacked: true
}
},
plugins: {
datalabels: {
anchor: context => {
let bar = context.chart.getDatasetMeta(context.datasetIndex).data[context.dataIndex].getProps().height;
document.getElementById('myHeight').innerHTML = bar;
const threshold = 6;
if (bar + threshold > context.chart.chartArea.bottom) {
return 'end'
}
return 'center'
}
}
}
}
});
The behaviour comes from this part in the code:
const properties = {
horizontal,
base: vpixels.base,
enableBorderRadius: !stack || isFloatBar(parsed._custom) || (me.index === stack._top || me.index === stack._bottom),
x: horizontal ? vpixels.head : ipixels.center,
y: horizontal ? ipixels.center : vpixels.head,
height: horizontal ? ipixels.size : undefined,
width: horizontal ? undefined : ipixels.size
};
It sets the height on undefined for normal bar charts and the width on undefined on horizontal bar charts. Putted in a pr (https://github.com/chartjs/Chart.js/pull/9208) for fix so this should be fixed by the next release of chart.js
Then to get the bar height you have to change your mode to index and then you can use this function to get the total bar height:
onClick: function(event) {
var bar = this.getElementsAtEventForMode(event, 'index', {intersect: true}, true);
if (!bar.length) return; //return if not clicked on bar
var barHeight = bar.reduce((acc , val) => (acc + val.element.height), 0)
document.getElementById('myHeight').innerHTML = barHeight;
}
Example: https://codepen.io/leelenaleee/pen/qBrpLjX

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.

Chart.js xAxis linear scale : strange behavior

I'm trying to use linear scale on x-axis in my chart.js chart.
I add some code beause stackoverflow makes it obligatory when adding a jsfiddle url, but I don't see the point :
var options={
scales:{
xAxes:[{ type: "linear"}]
}
};
I'm getting a very strange chart (2nd one) : http://jsfiddle.net/t0krmau8/
In the first chart, I'd like to get more space between 2 and 4 (2 times more space than between 1 and 2), that's why I'm using a linear scale.
Am I using the linear scale wrong? Or should I use something else?
Thanks
You're not providing the data in correct format for the scatter line plot.
The correct format to provide the data is described by the following example from Chart.js Docs.
var scatterChart = new Chart(ctx/* your canvas context*/, {
type: 'line',
data: {
datasets: [{
label: 'Scatter Dataset',
data: [{
x: -10,
y: 0
}, {
x: 0,
y: 10
}, {
x: 10,
y: 5
}]
}]
},
options: {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
}
}
});
source
I think the x and y should be separable into different arrays, but you can always do a combination step and combine them into objects.

Categories

Resources