I was able to add an offset to the X Labels but I would like to add an offset to all the points in the dataset. Is it possible?
This is the code I'm using:
var myChart = new Chart.Line(ctx, {
type: 'line',
data: {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", ""],
datasets: [{
data: [5, 10.5, 18.2, 33.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null],
pointLabelFontSize : 4,
borderWidth: 2,
fill: false,
lineTension: .3,
borderColor: "#f37029",
borderCapStyle: 'round',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'bevel',
pointBorderColor: "#f37029",
pointBackgroundColor: "#f37029",
pointBorderWidth: 1,
pointHoverRadius: 4,
pointHoverBackgroundColor: "rgba(220,220,220,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 4,
pointHitRadius: 10,
spanGaps: false,
}]
},
options: {
scales: {
xAxes: [{
gridLines: {
offsetGridLines: true,
display: false,
borderDash: [6, 2],
tickMarkLength:5
},
ticks: {
fontSize: 8,
labelOffset: 10,
maxRotation: 0
}}],
yAxes: [{
gridLines: {
display:false
},
ticks: {
beginAtZero: true,
max: 200,
min: 0,
stepSize: 20,
fontSize: 8
}
}]
},
legend: {
display: false
},
responsive: false,
maintainAspectRatio: true
}
});
I would like to apply that offset to all the points, in the image I just added an arrow to the JAN/DEC but I would like to apply it to all of them.
I tried adding a null data, the problem is that I don't want to show the first dashed grid.
Any ideas? Thanks in advance.
Check out - http://www.chartjs.org/docs/latest/axes/cartesian/ .
In chapter "Common Configuration",there is a Boolean attribute offset. Default value is false (except in case of bar chart)
If true, extra space is added to the both edges and the axis is scaled to fit into the chart area. This is set to true in the bar chart by default.
So you can just set it to true, and it should work.
You can achieve this using Chart.js plugins. They let you handle specific events triggered during the chart creation (beforeInit, afterUpdate, afterDraw ...) and are also easy to implement :
Chart.pluginService.register({
afterUpdate: function(chart) {
// This will be triggered after every update of the chart
}
});
Now you just have to loop through your dataset data model (the property used to draw charts) and add the offset you want :
Chart.pluginService.register({
afterUpdate: function(chart) {
// We get the dataset and set the offset here
var dataset = chart.config.data.datasets[0];
var offset = 20;
// For every data in the dataset ...
for (var i = 0; i < dataset._meta[0].data.length; i++) {
// We get the model linked to this data
var model = dataset._meta[0].data[i]._model;
// And add the offset to the `x` property
model.x += offset;
// .. and also to these two properties
// to make the bezier curve fits the new graph
model.controlPointNextX += offset;
model.controlPointPreviousX += offset;
}
}
});
You can see your example working on this jsFiddle and here is its result :
Leading on from the answer given by 'tektiv' I needed a similar solution but one that works for RESPONSIVE CHARTS.
So instead of using fixed measurements for the given offset shown in tektiv's plugin, we first count the number of objects in the dataset array. We then divide the chart.width by the number of objects in the array to give us equal segments, then in order to define the half way point between each grid line, we divide that sum by a factor of 2.
Note 1: You could also replace the factor of 2 to a variable so the user could chose the portion of offset needed.
Note 2: I've placed the plugin code within the chart script given I don't want this as a global affect by registering a global plugin.
Note 3: This is second re-edit of my solution given the plugin code I partially copied from the answer given by 'tektiv' above was only firing successfully for the first time, but then when re-loading a new instance of the chart I experienced some null errors on the dataset._meta (worth also seeing answer here on this particular topic as this helped me fix and finalize my answer: Dataset._meta[0].dataset is null in ChartJS
Code example:
<script>
var myChart;
function drawChart() {
var ctx = document.getElementById('myChart').getContext('2d');
ctx.innerHTML = '';
if (myChart != null) {
myChart.destroy();
}
var datasetArray = [5, 10.5, 18.2, 33.9, 121.2, 184.9, 179.9, 196.1, 158.3, 166.3, 66.4, 20.6, null];
myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC", ""],
datasets: [{
data: datasetArray,
borderWidth: 2,
borderColor: "#f37029",
pointBorderColor: "#f37029",
pointBackgroundColor: "#f37029",
pointHitRadius: 10,
spanGaps: false,
}]
},
plugins: [{
afterUpdate: function (chart, options) {
//..
var dataset = chart.config.data.datasets[0];
// Get the number of objects in the dataset array.
var noDataPoints = datasetArray.length;
//alert(noDataPoints); // testing only, you'll notice that this
// alert would fire each time the responsive chart is resized.
var xOffset = (chart.width / noDataPoints) / 2;
for (var i = 0; i < dataset.data.length; i++) {
for (var key in dataset._meta) {
var model = dataset._meta[key].data[i]._model;
model.x += xOffset;
model.controlPointNextX += xOffset;
model.controlPointPreviousX += xOffset;
}
}
}
}],
options: {
scales: {
xAxes: [{
gridLines: {
offsetGridLines: false,
display: true,
},
ticks: {
fontSize: 8,
maxRotation: 0
}
}],
yAxes: [{
gridLines: {
display: true
},
ticks: {
beginAtZero: true,
}
}]
},
legend: {
display: false
},
responsive: true,
maintainAspectRatio: true
}
});
}
</script>
First screenshot below shows the responsive chart stretched to a wide screen view:
Second screenshot shows the responsive chart resized to a smaller and more conventional window size:
Related
I'm trying to make a a combination of a candlestick chart (representing stock data) and a bar chart (representing volume).
I already have them displayed on one chart but the display and layout I'm having trouble with.
For one, the candlestick and bar data are placed side-by-side rather than stacked on top of each other. Another error is the scale of the volume data for the bar chart is not represented properly in the y-axis (which uses data from candlesticks as basis).
Here is my current code to render the chart:
chart = new Chart(ctx, {
type: 'candlestick',
data: {
labels: labelsData,
datasets: [{
label: "My Data",
data: chartData
},
{
label: 'Volume',
data: volData,
type: 'bar'
}]
}
});
labelsData contains the Date values for each item entry
chartData contains JSON object with c,h,l,o,t (close,high,low,open,date) to
represent stock data for each item entry
volData is an array containing numbers to represent volume for each item entry
What should I add to make the candlesticks and bars placed on the same column, as well as have the bars have their own scale so they do not overshoot the height of the chart?
It seems you need to scale the volume data since it's two different value units in Y,
It seems like currentlty there isn't support for this in chartJs I created a feature request, follow the link to see the two issues that were closed due to this.
https://github.com/apexcharts/apexcharts.js/issues/2068
With default configuration you're not easily able to add barcharts.
Here is steps you need to do;
Base config:
const config = {
// type: 'candlestick', // you must remove this, this option is braking the chart
data: {
datasets: []
},
options: {
parsing: false, // must be here, solves another stupid problem
spanGaps: true, // for better performance
animation: false, // for better performance
pointRadius: 0, // for better performance
plugins: {
title: {
display: false,
text: 'Fiyat Grafiği'
},
},
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
type: 'timeseries',
},
y: {
type: 'linear',
},
volume: {
type: 'linear',
beginAtZero: true,
position: 'right',
max: maxVolume * 10, // maxVolume should be the maximum number of volumes
grid: {
display: false, // for better presentation
},
ticks: {
display: false, // for better presentation
},
}
},
interaction: {
intersect: false,
mode: 'index',
},
}
};
Second step is preparing the datasets;
let dataSets = [
{
type: 'candlestick', // this must stay
label: 'Financial Graph',
data: data['klines'].map(function (kline) {
return {
'x': moment(kline['from']),
'o': kline['open_price'],
'c': kline['close_price'],
'h': kline['high_price'],
'l': kline['low_price']
};
}),
color: {
up: 'rgb(26, 152, 129)', // those colors are better than defaults
down: 'rgb(239, 57, 74)', // those colors are better than defaults
unchanged: '#999', // those colors are better than defaults
},
borderColor: {
up: 'rgb(26, 152, 129)',
down: 'rgb(239, 57, 74)',
unchanged: '#999',
},
order: 10,
yAxisID: 'y', // this must stay
},
{
type: 'bar',
label: 'Volume',
data: data['klines'].map(function (kline) {
return {
'x': moment(kline['from']), // i used moment, feel free to use your own time library
'y': kline.quote_asset_volume,
}
}),
backgroundColor: data['klines'].map(function (kline) {
return kline.open_price < kline.close_price ? 'rgb(26, 152, 129)' : 'rgb(239, 57, 74)' // for better presentation
}),
borderColor: '#fff',
borderWidth: 1,
order: 12,
yAxisID: 'volume', // this must stay
barPercentage: 0.5, // this must stay
barThickness: 6, // this must stay
maxBarThickness: 8, // this must stay
},
]
Result;
First of all, sorry for combining multiple questions in to one. The only reason is all of them are related (hopefully) to one particular chart type.
QUESTION 1: The horizontal baseline is not appearing.
Actual
Requirement
QUESTION 2: Fraction values.
Is there a way to display only integers? I don't need fraction values in grid lines. Please see the above screenshot.
QUESTION 3: Vertical Line annotation text placement.
The annotation text for the vertical black bold line is coming to the right of it hence it is getting cut. Please see the second chart in the following screenshot
This actually needs to appear like this (to the bottom of the line and the annotation text needs to come a bit below base line labels). Please see the following screenshot
Is that is not possible, is there any way to place the annotation text to the left of this line so that it doesn't get cut and the entire annotation text stays inside the chart?
Below is the chart script I am using:
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawHorizontalChart_portal_name_stella_york_horz_month_points);
function drawHorizontalChart_portal_name_stella_york_horz_month_points() {
var data = google.visualization.arrayToDataTable([
["", "Goal Achieved", {role: 'style'}, "GOAL 13.1 points", {role: 'style'}, {role: 'annotation'}],
["", 1.5, "opacity: .75;", 13.1, "opacity: 0;", "GOAL 13.1 points"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}, 3, 4, 5]);
var options = {
title: '',
width: '100%',
height: 120,
chartArea: {
width: '90%',
height: 70
},
hAxis: {
title: '',
minValue: 0,
gridlines: {
count: 6
}
},
bar: {
groupWidth: "60%"
},
legend: {
position: "top"
},
series: {
0: {
color: '#70b5c5',
visibleInLegend: false
}, // Goal Achieved
1: {
color: '#000000',
type: 'line',
annotations: {
textStyle: {
color: '#000000',
textPosition: 'vertical'
},
stemColor: 'none',
vertical: true
}
} // Target Goal
}
};
var chart = new google.visualization.BarChart(document.getElementById("portal-name-stella-york-horz-month-points"));
chart.draw(view, options);
drawVAxisLine(chart, 13.1);
}
jQuery(window).resize(function() {
drawHorizontalChart_portal_name_stella_york_horz_month_points();
});
function drawVAxisLine(chart, value) {
var layout = chart.getChartLayoutInterface();
var chartArea = layout.getChartAreaBoundingBox();
var svg = chart.getContainer().getElementsByTagName('svg')[0];
var xLoc = layout.getXLocation(value)
svg.appendChild(createLine(xLoc, chartArea.top + chartArea.height, xLoc, chartArea.top, '#000000', 2)); // axis line
}
function createLine(x1, y1, x2, y2, color, w) {
var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', x1);
line.setAttribute('y1', y1);
line.setAttribute('x2', x2);
line.setAttribute('y2', y2);
line.setAttribute('stroke', color);
line.setAttribute('stroke-width', w);
return line;
}
1) horizontal baseline
the horizontal baseline does not appear because you have a string value in the first column
this creates a discrete axis
// string used here --> ["", 1.5, "opacity: .75;", 13.1, "opacity: 0;", "GOAL 13.1 points"]
instead, use a continuous x-axis (number, date, etc...)
// number --> [1, 1.5, "opacity: .75;", 13.1, "opacity: 0;", "GOAL 13.1 points"]
in order to hide the axis label, as done using the string, we can provide custom axis ticks
we can use object notation to provide both the value (v:) and the formatted value (f:)
which allows us to provide an empty string for the formatted value
just make sure the tick value matches the value provided in the first column above.
vAxis: {
gridlines: {
color: 'transparent'
},
ticks: [{v: 1, f: ''}]
}
note: a continuous axis will also cause other gridlines to appear,
we can remove those by making them transparent...
2) Fraction values
we can provide a format string for the axis labels...
hAxis: {
format: '0' // <-- format as integer
},
3) annotation text placement
the only available option here is stem.length
we can provide a negative value to move the annotation to the left...
stem: {
color: 'transparent',
length: -128
},
however, the actual position will not remain constant as the chart is resized
when the chart is smaller, the text will be farther away from the line (larger closer).
instead, we can manually move the annotation text, on the chart's 'ready' event.
but we should still use a negative stem length, to ensure the annotation appears to the left, and prevent from being cut. otherwise, we'll end up moving a cut annotation.
and since we're moving the annotation below the axis,
we need to increase chartArea.bottom or else it will be cut there as well.
finally, the chart will reset the annotation's position on any interactivity,
such as hover. we must use a MutationObserver to keep the annotation in the new position.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(drawHorizontalChart_portal_name_stella_york_horz_month_points);
function drawHorizontalChart_portal_name_stella_york_horz_month_points() {
var data = google.visualization.arrayToDataTable([
["", "Goal Achieved", {role: 'style'}, "GOAL 13.1 points", {role: 'style'}, {role: 'annotation'}],
[1, 1.5, "opacity: .75;", 13.1, "opacity: 0;", "GOAL 13.1 points"]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}, 3, 4, 5]);
var options = {
title: '',
width: '100%',
height: 132,
chartArea: {
height: '100%',
width: '100%',
top: 36,
left: 18,
right: 18,
bottom: 48
},
hAxis: {
title: '',
minValue: 0,
gridlines: {
count: 6
},
format: '0'
},
bar: {
groupWidth: "60%"
},
legend: {
position: "top"
},
series: {
0: {
color: '#70b5c5',
visibleInLegend: false
}, // Goal Achieved
1: {
color: '#000000',
type: 'line',
annotations: {
textStyle: {
color: '#000000'
},
stem: {
color: 'transparent',
length: -128
},
vertical: true
}
} // Target Goal
},
vAxis: {
gridlines: {
color: 'transparent'
},
ticks: [{v: 1, f: ''}]
}
};
var chart = new google.visualization.BarChart(document.getElementById("portal-name-stella-york-horz-month-points"));
google.visualization.events.addListener(chart, 'ready', function () {
// get x location of goal
var layout = chart.getChartLayoutInterface();
var xLoc = drawVAxisLine(chart, layout, data.getValue(0, 3));
// prevent annotation reset
var observer = new MutationObserver(function () {
var annotationText = data.getValue(0, data.getNumberOfColumns() -1);
Array.prototype.forEach.call(chart.getContainer().getElementsByTagName('text'), function(annotation) {
// find annotation
if ((annotation.textContent === annotationText) &&
(annotation.getAttribute('fill') === options.series[1].annotations.textStyle.color)) {
// move annotation
annotationBounds = annotation.getBBox();
annotation.setAttribute('x',
xLoc - (annotationBounds.width / 2)
);
annotation.setAttribute('y',
layout.getYLocation(0) + (parseInt(annotation.getAttribute('font-size')) * 3)
);
}
});
});
observer.observe(chart.getContainer(), {
childList: true,
subtree: true
});
});
chart.draw(view, options);
}
jQuery(window).resize(function() {
drawHorizontalChart_portal_name_stella_york_horz_month_points();
});
function drawVAxisLine(chart, layout, value) {
var chartArea = layout.getChartAreaBoundingBox();
var svg = chart.getContainer().getElementsByTagName('svg')[0];
var xLoc = layout.getXLocation(value)
svg.appendChild(createLine(xLoc, chartArea.top + chartArea.height, xLoc, chartArea.top, '#000000', 2)); // axis line
return xLoc;
}
function createLine(x1, y1, x2, y2, color, w) {
var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
line.setAttribute('x1', x1);
line.setAttribute('y1', y1);
line.setAttribute('x2', x2);
line.setAttribute('y2', y2);
line.setAttribute('stroke', color);
line.setAttribute('stroke-width', w);
return line;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="portal-name-stella-york-horz-month-points"></div>
note: you should wait for the 'ready' event before making any changes / adding elements to the chart.
I'm trying to make a chart that shows the trade volumes for the currencies CAD and DKK:
https://jsfiddle.net/askhflajsf/g7mht8tt/
Using data from these files:
http://api.bitcoincharts.com/v1/csv/localbtcCAD.csv.gz
http://api.bitcoincharts.com/v1/csv/localbtcDKK.csv.gz
But, how do I deal with the fact that these datasets have different dates/UNIX timestamps? My chart above has DKK's data "forced into" CAD's timestamps -- but this can't be right can it? What should I do?
Note: The below snippet doesn't have the full data due to StackOverflow's body limit.
// Disable pointers
Chart.defaults.global.elements.point.radius = 0;
Chart.defaults.global.elements.point.hoverRadius = 0;
var myChartData = {
// Timestamps from http://api.bitcoincharts.com/v1/csv/localbtcCAD.csv.gz
labels: [1363085391, 1363088879, 1363120475, 1363132522, 1363214378],
// Timestamps from http://api.bitcoincharts.com/v1/csv/localbtcDKK.csv.gz
//labels: [1366383202, 1366471506, 1368121200, 1375783458, 1375953845],
datasets: [{
label: "CAD",
borderColor: "#FF0000",
fill: false,
borderWidth: 1,
data: [5.432200000000, 4.981800000000, 1.768000000000, 1.000000000000, 4.000000000000]
},
{
label: "DKK",
borderColor: "#000000",
fill: false,
borderWidth: 1,
data: [1.000000000000, 2.700000000000, 2.187400000000, 1.000000000000, 4.000000000000]
}
]
};
var ctx = document.getElementById("mychart").getContext("2d");
new Chart(ctx, {
type: 'line',
data: myChartData,
options: {
scales: {
xAxes: [{
type: "time",
ticks: {
minRotation: 90
}
}]
}
}
});
<script src="https://rawgit.com/chartjs/chartjs.github.io/master/dist/master/Chart.bundle.min.js"></script>
<canvas id="mychart"></canvas>
I'm trying to map non numeric y and x and for some reason it does not work.
E.g.
xLabels: ["January", "February", "March", "April", "May", "June", "July"],
yLabels: ['Request Added', 'Request Viewed', 'Request Accepted', 'Request Solved', 'Solving Confirmed'],
And when i try to change:
data: ['Request Added', 'Request Viewed']
with
data: [{x: "January", y: 'Request Added'}, ...]
Graph does not show a thing
Also i tried to use scales.yAxis.ticks.callback to modify and map against an array but that didnt work out either.
[0: 'Request Added', 1: 'Request Viewed']
EDIT: Essentially I need something like this
Request Added x x
Request Viewed x
Request Accepted x x
January, Feb, March
Basically a copy of this: https://answers.splunk.com/answers/85938/scatter-plot-with-non-numeric-y-values.html
Which also suggests to map against an array, but the callback in Y-ticks makes no freaking sense.. ? As i add labelY : [1,2,3,4,5,6] The Third argument of callback "values" is equal to [-2-1 0 1 2].
In order to use a category scale for both the X and Y axis, you must use the traditional data format of an array of values. Per the chart.js api docs...
Scatter line charts can be created by changing the X axis to a linear axis. To use a scatter chart, data must be passed as objects containing X and Y properties
This implies that you can only use the data format {x: ' ', y: ' '} when at least the X axis is a linear scale (but I'm betting it only works if both the X and Y axis are linear).
Since you are limited to only using an array of values for your data, you must use at least 2 datasets in order to plot multiple values on the X axis (like what you are trying to do).
Here is a chart configuration that gives what you are looking for.
var ctx = document.getElementById("canvas").getContext("2d");
var myLine = new Chart(ctx, {
type: 'line',
data: {
xLabels: ["January", "February", "March", "April", "May", "June", "July"],
yLabels: ['Request Added', 'Request Viewed', 'Request Accepted', 'Request Solved', 'Solving Confirmed'],
datasets: [{
label: "My First dataset",
data: ['Request Added', 'Request Viewed', 'Request Added'],
fill: false,
showLine: false,
borderColor: chartColors.red,
backgroundColor: chartColors.red
}, {
label: "My First dataset",
data: [null, 'Request Accepted', 'Request Accepted'],
fill: false,
showLine: false,
borderColor: chartColors.red,
backgroundColor: chartColors.red
}]
},
options: {
responsive: true,
title:{
display: true,
text: 'Chart.js - Non Numeric X and Y Axis'
},
legend: {
display: false
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
type: 'category',
position: 'left',
display: true,
scaleLabel: {
display: true,
labelString: 'Request State'
},
ticks: {
reverse: true
},
}]
}
}
});
You can see what it looks like from this codepen.
If you are for whatever reason tied to using the {x: ' ', y: ' '} dataformat, then you will have to change both your scales to linear, map your data to numerical values, then use the ticks.callback property to map your numerical ticks back to string values.
Here is an example that demonstrates this approach.
var xMap = ["January", "February", "March", "April", "May", "June", "July"];
var yMap = ['Request Added', 'Request Viewed', 'Request Accepted', 'Request Solved', 'Solving Confirmed'];
var mapDataPoint = function(xValue, yValue) {
return {
x: xMap.indexOf(xValue),
y: yMap.indexOf(yValue)
};
};
var ctx2 = document.getElementById("canvas2").getContext("2d");
var myLine2 = new Chart(ctx2, {
type: 'line',
data: {
datasets: [{
label: "My First dataset",
data: [
mapDataPoint("January", "Request Added"),
mapDataPoint("February", "Request Viewed"),
mapDataPoint("February", "Request Accepted"),
mapDataPoint("March", "Request Added"),
mapDataPoint("March", "Request Accepted"),
],
fill: false,
showLine: false,
borderColor: chartColors.red,
backgroundColor: chartColors.red
}]
},
options: {
responsive: true,
title: {
display: true,
text: 'Chart.js - Scatter Chart Mapping X and Y to Non Numeric'
},
legend: {
display: false
},
scales: {
xAxes: [{
type: 'linear',
position: 'bottom',
scaleLabel: {
display: true,
labelString: 'Month'
},
ticks: {
min: 0,
max: xMap.length - 1,
callback: function(value) {
return xMap[value];
},
},
}],
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Request State'
},
ticks: {
reverse: true,
min: 0,
max: yMap.length - 1,
callback: function(value) {
return yMap[value];
},
},
}]
}
}
});
You can see this in action at the same codepen.
I am trying to build graph.
My y-axis start with 0 here, I dont know how to configure it and why it is talking 0 - I see other post which mentioned scaleOverride:true, scaleStartValue:0.1, scaleStepWidth:5 - I dont know how to use that in my below code , how can configure y-axis in chart.js.
Any pointer would be
I have following code
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Dataset 1',
backgroundColor: "rgba(220,220,220,0.5)",
data: [6, 6, 6, 8, 6, 9, 8]
}]
};
function barChart() {
var context = document.getElementById('stacked').getContext('2d');
var myBar = new Chart(context, {
type: 'bar',
data: barChartData,
options: {
title:{
display:true,
text:"Chart.js Bar Chart - Stacked"
},
tooltips: {
mode: 'label'
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
};
$(document).ready(function() {
$(document).ready(barChart);
});
Thank you guys for helping, I observed that chart.js will automatically take value for y-axis based on your data, you can change y/x-axis setting under Options > Scales , I also needed to change step size of y-axis and get rid of x-axis grid line,"ticks" is something I was looking for, here is my sample code and steps to achieved all these.
Step 1) Canvas this is place holder where your chart will display on JSP
<canvas width="1393px;" height="500px;" id="stacked"></canvas>
Step 2) Create sample datasets (this is JSON you need to create based on your requirement but make sure you provide exact the same formated JSON response as given below along with your data.
var barChartData = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: 'Dataset 1',
backgroundColor: "red",
data: [9, 6, 6, 8, 6, 9, 8]
},
{
label: 'Dataset 1',
backgroundColor: "rgba(225,226,228,0.5)",
data: [9, 6, 6, 8, 6, 9, 8]
}]
};
or you can call JSON from controller inside script as below
var jsonArry = <%=request.getAttribute("jsonArry")%>;
Step 3) call that JSON which you have created at step 2
function barChart(){
var context = document.getElementById('stacked').getContext('2d');
var myBar = new Chart(context, {
type: 'bar',
data: jsonArry,
options: {
tooltips: {
mode: 'label'
},
responsive: true,
scales: {
xAxes: [{
ticks:{
stepSize : 10,
},
stacked: true,
gridLines: {
lineWidth: 0,
color: "rgba(255,255,255,0)"
}
}],
yAxes: [{
stacked: true,
ticks: {
min: 0,
stepSize: 1,
}
}]
}
}
});
};
Hope this will help , for reference I have used following documentation Chart JS
Thanks.
Just remove the stacked option and it will stop starting from 0 (unless your data starts from 0).
Related fiddle - http://jsfiddle.net/rsyk9he0/
For stacked charts, Chart.js builds a list of positive and negative sums for each stack (bar) and then uses that to figure out the scale min and max values. If there are no negative values, the list of negative sums is a list of 0s. This forces the scale min to be 0.
scaleStartValue, scaleStepWidth, etc. are options from v1.x of Chart.js. You are using v2.x. See How to make integer scale in Chartjs for the 2.x equivalents.