Charts.js - How to create a custom X axis - javascript

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

Related

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.

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.

Handle X-axis label position in chart js

Please look into this fiddle
If you resize the output window you will notice that the labels of x-axis becomes slanted. which is fine for me. But if you notice that the end position of label is center of bar. I want the end position of label to be the right-side end of bar. How can achieve this?
My config is
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["2 Jan", "9 Jan", "16 Jan", "23 Jan", "30 Jan", "6 Feb", "13 Feb"],
datasets: [{
data: [6, 87, 56, 15, 88, 60, 12],
}]
},
options: {
legend: {
"display": false
},
tooltips: {
"enabled": false
},
scales: {
yAxes: [{
display: false,
gridLines: {
display : false
},
ticks: {
display: false,
beginAtZero:true
}
}],
xAxes: [{
gridLines: {
display : false
},
ticks: {
beginAtZero:true
}
}]
}
}
});
It is certainly possible to achieve a 'right' aligned scale tick label instead of the original 'center' aligned scale tick label, but unfortunately it is not very straight forward to implement. Let me walk you through how to do it and then provide an example.
1) First, since there is no configuration option to control this, we have to look at doing some sort of custom implementation. It turns out that the scale tick labels in a bar chart are rendered as part of the Category scale's draw method. Therefore, we must somehow overwrite this draw method to change to a new alignment.
2) According to the API there is a documented way to create new scale types, so we should be able to use a similar approach to extend the Category scale type and overwrite it's draw method.
Since all scales are wrapped up in the ScaleService we have to use the below approach to extend an existing scale type.
var CategoryRightAligned = Chart.scaleService.getScaleConstructor('category').extend({});
3) Now its just a matter of figuring out what part of the draw method we need to modify. After looking it over, it looks like we need to change the logic for calculating labelX (the pixel position to render the tick label). Here would be the new logic.
// current logic for getting pixel value of each label (we will use the logic below to
// adjust if necessary)
labelX = me.getPixelForTick(index, gridLines.offsetGridLines) + optionTicks.labelOffset;
// get a reference to the bar chart controller so we can determine the chart's bar width
var meta = me.chart.getDatasetMeta(0);
// use the bart chart controller to calculate the bar width
var barWidth = meta.controller.calculateBarWidth(meta.controller.getRuler());
// if the labels are rotated, then move the pixel location from the middle of the bar
// to the far right of the bar
if (labelRotationRadians != 0) {
labelX += barWidth / 2;
}
4) Now we just need to register our new scale and configure the chart to use it (instead of the bar chart default category scale).
Chart.scaleService.registerScaleType('categoryRightAligned', CategoryRightAligned, {position: 'bottom'});
xAxes: [{
type: 'categoryRightAligned',
gridLines: {
display : false,
offsetGridLines: true
},
ticks: {
beginAtZero:true,
}
}]
Refer to this jsfiddle example to see it in action and to see how everything fits together.

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.

Highcharts Speedometer, dataLabel for mileage counter

There are several examples with the Speedometer in Highcharts.
Is there a way, to show an additional dataLabel only, without dial in the gauge?
It could show a trip recorder, mileage counter or day counter.
I tried additional series and dataLabels, but could not get it running.
http://jsfiddle.net/uqa0t3xw
series: [{
name: 'mileage counter',
data: [],
dataLabels: {
x: 0, y: 20,
format: '{y:.0f} km',
}
}]
If you want to have an additional data label by adding another series and hiding the dial you can do so by setting the color of the dial to "transparent" (JSFiddle):
series: [
// Our "hidden" series
{
name: 'mileage counter',
data: [0],
dataLabels: {
x: 0, y: 50,
format: '{y:.0f} km',
},
dial: {
backgroundColor: 'transparent'
}
},
// ... Other series
]
Also note how the y value has to be big enough to not overlap with the other data labels. If it overlaps it will be hidden, since gauge has allowOverlap: false by default. Alternatively you could set that to true, but overlapping might not be pretty.
It should be noted that this can also be solved by creating your own div and placing it in the correct spot or perhaps copying the data label from the first series and moving it slightly.

Categories

Resources