score:5
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 :
score:2
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:
score:10
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.
Source: stackoverflow.com
Related Query
- How to add an offset to a dataset in Chart js
- How to add new dataset in line chart of chart.js by iterating over dictionary in JavaScript?
- How to add text inside the doughnut chart using Chart.js?
- Chart.js - How to set a line chart dataset as disabled on load
- How to add an on click event to my Line chart using Chart.js
- How to display Line Chart dataset point labels with Chart.js?
- Add DataSet Bar Chart - Chart.JS
- How to add second Y-axis for Bar and Line chart in Chart.js?
- How to add text in centre of the doughnut chart using Chart.js?
- How to add datas to chart js from javascript array itself?
- How to add panning to chart in chartjs?
- how to add a title to my ng2-charts bar chart
- Chart.JS: How to add Data to a specific dataset
- How to dynamically set ChartJs line chart width based on dataset size?
- How to add comma in this chart js
- How to add a dataset toggle to Chart.js?
- How to add gradient background to Line Chart [vue-chart.js]
- How can I add some text in the middle of a half doughnut chart in Chart.JS?
- How to add ChartJS code in Html2Pdf to view image
- How to draw a needle on a custom donut chart and add datapoints to the needle?
- How to add images to chart labels with vue-chartjs?
- How to add an image to a slice of a donut chart in chart.js?
- How to add background image in bar chart column in Chart.js?
- How to add label in chart.js for polar chart area
- How to add title inside doughnut chart in Angular Chart?
- ChartJS version 3 how to add percentage to pie chart tooltip
- Using chart js version 3, how to add custom data to external tooltip?
- How to add area with break on line chart with fill color
- How do I add time sourced from an external source as an X axis to a ChartJS graph?
- how to add FAHRENHEIT symbol in chart js donut chart
More Query from same tag
- In Chart.js set chart title, name of x axis and y axis?
- Data of same dataset don't have the same color in chartjs
- Gradient is too blurred in Chart.js Line Chart
- Chartjs charts drawing with the same colour after update
- Chart.js - Pie chart calculate sum of visible values after legend click
- chartjs-plugin-error-bars display error-bars without displaying label on a horizontalBar chart
- How to change the z-index of chartjs annotations label?
- Legend only show on force refresh of page-chartjs
- Download Chart.js graph from view
- Chart.js: Can datasets be overlaid in a bar chart? (Not the same as stacked)
- Chart.js: Display Custom Tooltips, always visible on stacked bar-chart
- Chart.js flickering
- Why is my Line Chart.JS starting in the middle?
- In chart.js bar chart, how do I label each bar within a category?
- ChartJs Bubble chart - on hover bubble becomes too big
- Chart JS no animation line chart
- The dataset for bar graph is not set properly using ng2 charts and ng5-slider in Angular
- How to set max ticks count in chart.js 3.*.*
- Chart.js Label Issue
- How to add label for ChartJs Legend
- I am having this error in charts v3 chartjs-chart-treemap: fontColor does not exist in type 'ChartDataset<"treemap", TreemapDataPoint[]>
- Problem extending data series in Chart.js
- chartjs - How to use differente color if value is lower than previous value?
- ChartJS 2.6 - Bar chart fixed height scrollable-X
- Change color of a single point by clicking on it - Chart.JS
- chartjs xaxis ticks with round values from shifted input data
- Chart.js - Plot line graph with X , Y coordinates and connected by line
- How do I use NuGet to install ChartJS?
- react-chartjs-2 (chart.js) Radar - Remove values?
- Plot dataset from MySQL with Chart.js and PHP