Chart JS - Use time for xAxes - javascript

i added this code
scales:
{
xAxes:
[{
type: 'time',
time:
{
unit: 'month',
displayFormats: { month: 'MM' },
max: '2017-10-09 18:43:53',
min: '2017-10-02 18:43:53'
}
}]
},
to the options but it does not work. Any ideas what i'm making wrong?
FIDDLE ->
https://jsfiddle.net/o473y9pw/

Since you wish to use time for x-axis, your labels array should be an array of date/time string (labels array is correspondent to x-axis).
You would also need to set the parser property (to parse the date/time correctly), and x-axis' ticks source to data (to properly generate x-axis ticks).
UPDATE
If you only have a min and max date then, you can create a nice little plugin to populate the labels (date) array dynamically, as such :
plugins: [{
beforeInit: function(chart) {
var time = chart.options.scales.xAxes[0].time, // 'time' object reference
// difference (in days) between min and max date
timeDiff = moment(time.max).diff(moment(time.min), 'd');
// populate 'labels' array
// (create a date string for each date between min and max, inclusive)
for (i = 0; i <= timeDiff; i++) {
var _label = moment(time.min).add(i, 'd').format('YYYY-MM-DD HH:mm:ss');
chart.data.labels.push(_label);
}
}
}]
note: moment.js is used to make calculations easier.
ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩
( for demonstration purposes, I've changed the time unit to day )
$(document).ready(function() {
new Chart(document.getElementById("chartBox"), {
type: 'line',
data: {
datasets: [{
data: [12, 19, 3, 5, 2, 3, 32, 15],
label: "",
borderWidth: 2,
borderColor: "#3e95cd",
fill: false,
pointRadius: 0
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
parser: 'YYYY-MM-DD HH:mm:ss',
unit: 'day',
displayFormats: {
day: 'ddd'
},
min: '2017-10-02 18:43:53',
max: '2017-10-09 18:43:53'
},
ticks: {
source: 'data'
}
}]
},
legend: {
display: false
},
animation: {
duration: 0,
},
hover: {
animationDuration: 0,
},
responsiveAnimationDuration: 0
},
plugins: [{
beforeInit: function(chart) {
var time = chart.options.scales.xAxes[0].time, // 'time' object reference
timeDiff = moment(time.max).diff(moment(time.min), 'd'); // difference (in days) between min and max date
// populate 'labels' array
// (create a date string for each date between min and max, inclusive)
for (i = 0; i <= timeDiff; i++) {
var _label = moment(time.min).add(i, 'd').format('YYYY-MM-DD HH:mm:ss');
chart.data.labels.push(_label);
}
}
}]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/moment#latest/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.min.js"></script>
<canvas id="chartBox"></canvas>

The dataset should be an array of objects with properties x for time and y for value.
$(document).ready(function() {
var data = [{
x: new moment().add(-10, "months"),
y: Math.random() * 100
},
{
x: new moment().add(-8, "months"),
y: Math.random() * 100
},
{
x: new moment().add(-6, "months"),
y: Math.random() * 100
},
{
x: new moment().add(-4, "months"),
y: Math.random() * 100
},
{
x: new moment().add(-2, "months"),
y: Math.random() * 100
},
{
x: new moment().add(-0, "months"),
y: Math.random() * 100
},
];
new Chart(document.getElementById("chartBox"), {
type: 'line',
data: {
datasets: [{
data: data,
borderColor: "#3e95cd",
fill: false
}]
},
options: {
scales: {
xAxes: [{
type: 'time'
}]
},
legend: false
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.0/Chart.bundle.min.js"></script>
<canvas id="chartBox"></canvas>
Fiddle

If the xAxis label is in date format use this code
time:
{
format: 'MM',
unit: 'month',
displayFormats: { month: 'MM' },
max: '2017-10-09 18:43:53',
min: '2017-10-02 18:43:53'
}
If the xAxis label is as what u used numerals use
time:
{
format: 'MM',
unit: 'month',
parser:'MM',
displayFormats: { month: 'MM' },
max: '2017-10-09 18:43:53',
min: '2017-00-02 18:43:53'
}

You might want to change a few things.
Your data should include time data.
If you set scale unit to be month, your min max should be more than one month to see the actual scales.
Here's simplified working example.
https://jsfiddle.net/f2xmkkao/

Related

ChartJS options.scales is being completely ignored

I am trying to make a chart which has years along the x-axis and dollar amounts along the y-axis. I finally got close to what I'm looking for, but I found that because the x coordinates are numbers, ChartJS is putting commas in them which looks really strange for years.
After some digging, I used the callbacks. options.plugin.tooltip.callbacks.label worked to let me remove commas in the tooltips, but when I use options.scales.x[0].ticks.callback to try to fix the labels on the bottom, not only does it not work, but I don't see the console.log statement in their ever being printed so it seems it's not even calling the callback. I've tried several variations of how to do the callback based on what I found online and on Stack Overflow which I think correspond to the different ways ChartJS did this in different versions. (I'm on version 3.5.1.)
Then, I realized that... none of the options under options.scales appear to have any effect. I change the min, the title, the tick settings (color to red, callback, etc.) and it has no effect. (This also explains why I was having trouble when using the line chart and had to switch to scatter; apparently type: 'linear' wasn't being picked up nor did it do anything different when I set it to type: 'date' or whatever the exact working was for that.)
Meanwhile, the other options like options.showLine or options.elements do have an effect and I'm seeing the chart and not getting any errors in the console. So, it is picking up the options, just ignoring everything I have in options.scales.
Here is the relevant code:
// Sample data added to make this example self-contained
// This is my internal data format
let data = {
"Series1": [ {x: 2001, y: 100 }, {x: 2002, y: 110 }, {x: 2003, y: 107 }, ],
"Series2": [ {x: 2001, y: 107 }, {x: 2002, y: 102 }, {x: 2004, y: 95 }, ],
}
// Define data //////////////////////////////////////////////////////
// I convert data to format ChartJS wants and add a few options
let datasets = [];
for(let label in data) {
let c = colorIterator.next().value
datasets.push({
label: label,
data: data[label],
backgroundColor: c,
borderColor: c,
});
}
// Define options //////////////////////////////////////////////////////
let chartConfig = {
type: 'scatter',
data: { datasets: datasets, },
options: {
title: { display: false },
indexAxis: 'x', responsive: true, maintainAspectRatio: false,
showLine: true,
elements: {
line: { display: true, tension: 0, borderWidth: 1, fill: false, },
point: { radius: 3 }
},
interaction: { mode: 'x', },
scales: {
x: [{
type: 'linear',
min: 1995, max: (new Date()).getFullYear()+1, stepSize: 1,
title: { display: true, text: 'Year' },
ticks: {
display: true,
major: { enabled: true },
color: 'red',
callback: function(value, index, ticks) {
console.log(value);
return Chart.Ticks.formatters.numeric.apply(this, [value, index, ticks])
.replace(",","");
}
}
}],
y: [{
title: { display: true, text: '$' },
ticks: {
display: true,
color: 'red',
},
}],
},
plugins: {
tooltip: {
callbacks: {
label: function(context) {
let label = context.dataset.label || '';
if(label) {
let x = context.label.replace(",","");
let y = context.formattedValue;
return 'Year ' + x + ' "' + label + '": $' + y;
} else { return 'x'; }
},
},
},
},
}
};
// MAKE CHART //////////////////////////////////////////////////////
let mainChart = new Chart(document.getElementById(c.id), chartConfig);
As described in the docs the scales are not arrays. All the scales are objects in the scale object.
So you will need to change your code to this:
options: {
scales: {
x: {
// x options
},
y: {
// y options
},
}
}

Adjusting dates in X Axis Plotly

I was wondering how can you achieve the following:
I'm using a Date format of year and month ( i.e 2022-01), but Plotly is not providing an option to have a simple date value for the x Axis, Chart.JS actually allows you to define the date by month, so what is happening is that if you zoom in to one month, then you can see days and even hours, so how do I change that?
Secondly, is there a way to control how the X-axis is displayed?, for example perhaps when you have more than one year is better to show quarters, but as you zoom in for a 1-year period, then I would like to see every month display?, but I don't want to have more granularity, I would like to have only the month display in the graph
https://jsfiddle.net/60ucqz8w/
var Deals = {
x: ['2021-10', '2022-01', '2022-03', '2022-04', '2022-05', '2022-07', '2022-09'],
y: [11241, 234021, 26544, 28856, 70463, 28856, 155019],
name: 'Deals',
type: 'bar',
marker: {
color: 'rgb(0,131,117)',
}
};
var Leads = {
x: ['2022-03', '2022-04', '2022-05', '2022-06', '2022-07', '2022-08', '2022-11', '2023-01', '2023-02'],
y: [7255, 5155, 61950, 63000, 5155, 19845, 20905, 5155, 15750],
name: 'Leads',
type: 'bar',
marker: {
color: 'rgb(160,220,210)',
}
};
var Cumulative = {
x: ['2021-10', '2022-01', '2022-03', '2022-04', '2022-05', '2022-07', '2022-09'],
y: [11241, 245262, 271806, 300662, 371125, 399981, 555000],
name: 'Cumulative Deals',
type: 'line',
marker: {
color: 'rgb(0,131,117)',
}
};
var data = [Deals,Leads,Cumulative];
var layout = {
title: "Sales Forecast",
barmode: 'stack',
xaxis: {
autorange: true,
rangeselector: {
buttons: [{
step: 'all'
},
{
count: 1,
label: 'YTD',
step: 'year',
stepmode: 'todate'
},
{
count: 6,
label: '6m',
step: 'month',
stepmode: 'todate'
}]},
rangeslider: { },
type: 'date',
tickfont:{
size: 14
},
},
yaxis: {
tickfont:{size: 14}
}
};
Plotly.newPlot('DivBarChart', data,layout);```
You code was mostly right the only thing that needed fixing is the scrollZoom: true. The code won't work unless you put scrollZoom: true because the function won't be active unless specified. You need this so you can enable it for your graph. You need to select the timeframe using you mouse. Click and drag to see your timeframe.
var Deals = {
x: ['2021-10', '2022-01', '2022-03', '2022-04', '2022-05', '2022-07', '2022-09'],
y: [11241, 234021, 26544, 28856, 70463, 28856, 155019],
name: 'Deals',
type: 'bar',
marker: {
color: 'rgb(0,131,117)',
}
};
var Leads = {
x: ['2022-03', '2022-04', '2022-05', '2022-06', '2022-07', '2022-08', '2022-11', '2023-01', '2023-02'],
y: [7255, 5155, 61950, 63000, 5155, 19845, 20905, 5155, 15750],
name: 'Leads',
type: 'bar',
marker: {
color: 'rgb(160,220,210)',
}
};
var Cumulative = {
x: ['2021-10', '2022-01', '2022-03', '2022-04', '2022-05', '2022-07', '2022-09'],
y: [11241, 245262, 271806, 300662, 371125, 399981, 555000],
name: 'Cumulative Deals',
type: 'line',
marker: {
color: 'rgb(0,131,117)',
}
};
var data = [Deals, Leads, Cumulative];
var layout = {
title: "Sales Forecast",
barmode: 'stack',
};
Plotly.newPlot('DivBarChart', data, layout, {
scrollZoom: true
});
<div class="col-sm-4">
<div id='DivBarChart' class="container"></div>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</div>
See scroll and zoom in or plotly.js docs for more information.

Chart.js : How I change the x axes ticks labels alignment in any sizes?

How can I move my labels on my x axes in between another x axes label. Nothing seems to work and I was unable to find anything on the docs. Is there a workaround? I'm using line chart time series.
https://www.chartjs.org/samples/latest/scales/time/financial.html
Currently, with the code I have its generating the figure below:
var cfg = {
elements:{
point: {
radius: 4
}
},
data: {
datasets: [
{
label: 'vsy',
backgroundColor: color(window.chartColors.red).alpha(0.5).rgbString(),
borderColor: window.chartColors.red,
data: firstData,
type: 'line',
pointRadius: 2,
fill: false,
lineTension: 0,
borderWidth: 2
},
{
label: 'de vsy',
backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
borderColor: window.chartColors.blue,
data: dataMaker(15),
type: 'line',
pointRadius: 2,
fill: false,
lineTension: 0,
borderWidth: 2
}
],
},
options: {
animation: {
duration: 0
},
scales: {
xAxes: [{
type: 'time',
distribution: 'series',
offset: true,
time: {
unit: 'month',
displayFormats: {
month: 'MMM'
}
},
ticks: {
autoSkip: true,
autoSkipPadding: 75,
sampleSize: 100
},
}],
yAxes: [{
gridLines: {
drawBorder: false
}
}]
},
tooltips: {
intersect: false,
mode: 'index',
}
}
};
This is what I have now:
I want the labels on the x-axis to be on center instead of below the y axis grid line.
Thanks to uminder, with his comment it solves the issue but now I have a conflicting tooltip which lie on a same grid. When I hover to april line first point it shows me mar 30 which lies just above it and vice versa.
I fixed it by changing the mode to nearest but why is it activating the another point?
The option you're looking for is offsetGridLines.
If true, grid lines will be shifted to be between labels.
xAxes: [{
...
gridLines: {
offsetGridLines: true
}
In most cases, this produces the expected result. Unfortunately it doesn't work for time axes as documented in Chart.js issue #403. Thanks to Antti Hukkanen, there exists a workaround.
Please have a look at below runnable code snippet to see how it works.
function generateData() {
var unit = 'day';
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
function randomPoint(date, lastClose) {
var open = randomNumber(lastClose * 0.95, lastClose * 1.05).toFixed(2);
var close = randomNumber(open * 0.95, open * 1.05).toFixed(2);
return {
t: date.valueOf(),
y: close
};
}
var date = moment().subtract(1, 'years');
var now = moment();
var data = [];
for (; data.length < 600 && date.isBefore(now); date = date.clone().add(1, unit).startOf(unit)) {
data.push(randomPoint(date, data.length > 0 ? data[data.length - 1].y : 30));
}
return data;
}
var TimeCenterScale = Chart.scaleService.getScaleConstructor('time').extend({
getPixelForTick: function(index) {
var ticks = this.getTicks();
if (index < 0 || index >= ticks.length) {
return null;
}
// Get the pixel value for the current tick.
var px = this.getPixelForOffset(ticks[index].value);
// Get the next tick's pixel value.
var nextPx = this.right;
var nextTick = ticks[index + 1];
if (nextTick) {
nextPx = this.getPixelForOffset(nextTick.value);
}
// Align the labels in the middle of the current and next tick.
return px + (nextPx - px) / 2;
},
});
// Register the scale type
var defaults = Chart.scaleService.getScaleDefaults('time');
Chart.scaleService.registerScaleType('timecenter', TimeCenterScale, defaults);
var cfg = {
data: {
datasets: [{
label: 'CHRT - Chart.js Corporation',
backgroundColor: 'red',
borderColor: 'red',
data: generateData(),
type: 'line',
pointRadius: 0,
fill: false,
lineTension: 0,
borderWidth: 2
}]
},
options: {
animation: {
duration: 0
},
scales: {
xAxes: [{
type: 'timecenter',
time: {
unit: 'month',
stepSize: 1,
displayFormats: {
month: 'MMM'
}
},
gridLines: {
offsetGridLines: true
}
}],
yAxes: [{
gridLines: {
drawBorder: false
}
}]
},
tooltips: {
intersect: false,
mode: 'index'
}
}
};
var chart = new Chart('chart1', cfg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="chart1" height="90"></canvas>
For chartJs v3 you can use offset property:
scales: {
x: {
grid: {
offset: true
}
},
...
}

How to make HighStock / HighChart scroll bar location default to the left hand side?

I am trying to make the HighStock chart's scroll bar default to the left hand side location. Essentially, I am looking at forecast data that starts from today's date. The chart defaults to a 3 month window, and I need this window's starting location to be from today. Here is an example plot:
I need the highlighted scroll bar to default to the left. I am working with a team in India on this issue, and they told me "it's not possible, and is a HighChart's limitation". I'm not saying they are wrong, but I really feel like it can be done without too much issue. Bellow is the js that generates my specific plot (not the same as the one pictured above).
$(function () {
var now = new Date();
var utc_timestamp = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
$.ajax({
type: 'GET',
url: '/Conductivity/ForecastPlot',
data: { USGSID: Source1Id },
success: function (jsonData) {
var BestCase = new Array();
var WorstCase = new Array();
for (var i = 0 ; i < jsonData.AverageForecastData.length ; i++) {
var BestData = new Object();
var WorstData = new Object();
BestData = jsonData.AverageForecastData[i];
WorstData = jsonData.MaximumForecastData[i];
BestCase.push(BestData.cond);
WorstCase.push(WorstData.cond)
}
$('#Forecast_Source_1').empty();
$('#Forecast_Source_1').highcharts('StockChart', {
rangeSelector: {
selected: 1,
},
chart: {
type: 'spline',
zoomType: 'x',
width: 630,
height: 300
},
xAxis: {
type: 'datetime',
tickInterval: 24 * 3600 * 1000 * 21,
title: {
text: 'Date'
}
},
yAxis: {
title: {
text: 'Conductivity'
}
},
credits: {
enabled: false
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function (e) {
}
}
},
marker: {
enabled:false,
lineWidth: 1
}
}
},
legend: {
enabled: true,
layout: 'horizontal',
borderWidth: 1
},
series: [{
name: 'WorstCase',
pointInterval: 24 * 3600 * 1000,
pointStart: utc_timestamp,
data: WorstCase,
color: '#FF0000'
},{
name: 'Expected',
pointInterval: 24 * 3600 * 1000,
pointStart: utc_timestamp,
data: BestCase
}]
});
}
});
});
I've taken a quick look at the API and I don't specifically see an option for this in the "scrollbar" option, but I am thinking of creating a custom zoom function that loads the appropriate window with the From: xx/xx/xx To: xx/xx/xx boxes when a user clicks on the 1m,3m,or 6m buttons.
Edit: Partial Solution
I have a partial solution that seems to be working great. Here is what I changed:
First of all, I know that all the data in my MySQL database is always rounded to the nearest day, so I made sure that the code was rounding also:
var now = new Date();
now.setHours(now.getHours()) + Math.round(now.getMinutes());
now.setMinutes(0);
var utc_timestamp_today = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
var utc_timestamp_3moFromNow = Date.UTC(now.getFullYear(), (now.getMonth() + 3), now.getDate(), 0, 0, 0, 0);
After adding this in, I simply added a "min" and "max" to my "xAxis" parameter.
xAxis: {
type: 'datetime',
tickInterval: 24 * 3600 * 1000 * 21,
min: utc_timestamp_today,
max: utc_timestamp_3moFromNow,
title: {
text: 'Date'
}
You can see the new plot below. This is the actual plots I am dealing with, and you can see how when the page first loads the scroll bar is now in the proper location:
Now my only remaining issue is that when the user goes and clicks on the 1m, 3m, 6m option the graph's window scroll bar will revert to being back at the right hand side. Does anyone know how I might solve this?
Final Working Solution:
$(function () {
var now = new Date();
now.setHours(0, 0, 0, 0);;
now.setMinutes(0);
var plus1mo = new Date();
plus1mo.setMonth((now.getMonth() + 1));
plus1mo.setHours(0, 0, 0, 0);
plus1mo.setMinutes(0);
var plus3mo = new Date();
plus3mo.setMonth((now.getMonth() + 3));
plus3mo.setHours(0, 0, 0, 0);
plus3mo.setMinutes(0);
var plus6mo = new Date();
plus6mo.setMonth((now.getMonth() + 6));
plus6mo.setHours(0, 0, 0, 0);
plus6mo.setMinutes(0);
var utc_timestamp_today = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
var utc_timestamp_1moFromNow = Date.UTC(plus1mo.getFullYear(), plus1mo.getMonth(), plus1mo.getDate(), 0, 0, 0, 0);
var utc_timestamp_3moFromNow = Date.UTC(plus3mo.getFullYear(), plus3mo.getMonth(), plus3mo.getDate(), 0, 0, 0, 0);
var utc_timestamp_6moFromNow = Date.UTC(plus6mo.getFullYear(), plus6mo.getMonth(), plus6mo.getDate(), 0, 0, 0, 0);
$.ajax({
type: 'GET',
url: '/Conductivity/ForecastPlot',
data: { USGSID: Source1Id },
success: function (jsonData) {
var BestCase = new Array();
var WorstCase = new Array();
for (var i = 0 ; i < jsonData.AverageForecastData.length ; i++) {
var BestData = new Object();
var WorstData = new Object();
BestData = jsonData.AverageForecastData[i];
WorstData = jsonData.MaximumForecastData[i];
BestCase.push(BestData.cond);
WorstCase.push(WorstData.cond)
}
$('#Forecast_Source_1').empty();
$('#Forecast_Source_1').highcharts('StockChart', {
rangeSelector: {
buttons: [{
type: 'month',
count: 1,
text: '1m'
}, {
type: 'month',
count: 3,
text: '3m'
}, {
type: 'month',
count: 6,
text: '6m'
}, {
type: 'all',
text: 'All'
}],
selected: 1
},
chart: {
type: 'spline',
zoomType: 'x',
width: 630,
height: 300
},
xAxis: {
type: 'datetime',
tickInterval: 24 * 3600 * 1000 * 21,
min: utc_timestamp_today,
max: utc_timestamp_3moFromNow,
title: {
text: 'Date'
},
events: {
afterSetExtremes: function (e)
{
if(e.trigger == "rangeSelectorButton" && e.rangeSelectorButton.text == "1m") {
setTimeout(function () {
Highcharts.charts[1].xAxis[0].setExtremes(utc_timestamp_today, utc_timestamp_1moFromNow)
}, 1);
}
else if(e.trigger == "rangeSelectorButton" && e.rangeSelectorButton.text == "3m") {
setTimeout(function () {
Highcharts.charts[1].xAxis[0].setExtremes(utc_timestamp_today, utc_timestamp_3moFromNow)
}, 1);
}
else if(e.trigger == "rangeSelectorButton" && e.rangeSelectorButton.text == "6m") {
setTimeout(function () {
Highcharts.charts[1].xAxis[0].setExtremes(utc_timestamp_today, utc_timestamp_6moFromNow)
}, 1);
}
}
}
},
yAxis: {
title: {
text: 'Conductivity'
}
},
credits: {
enabled: false
},
tooltip: {
shared: true,
crosshairs: true
},
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function (e) {
}
}
},
marker: {
enabled:false,
lineWidth: 1
}
}
},
legend: {
enabled: true,
layout: 'horizontal',
borderWidth: 1
},
series: [{
name: 'WorstCase',
pointInterval: 24 * 3600 * 1000,
pointStart: utc_timestamp_today,
data: WorstCase,
color: '#FF0000'
},{
name: 'Expected',
pointInterval: 24 * 3600 * 1000,
pointStart: utc_timestamp_today,
data: BestCase
}]
});
}
});
});
The trick was setting a "timeout" function to be called after HighCharts is doing all it's stuff. Only then do I set the min/max so that I can get the appropriate range. (By the way: It's Highcharts.charts[1] because I have 2 charts)
Set this in your xAxis
xAxis : {
events: {
setExtremes: function(e) {
if(typeof(e.rangeSelectorButton)!== 'undefined')
{ this.min= utc_timestamp_today;
this.max= utc_timestamp_3moFromNow;
}
}
}

How can I dynamically update pointStart series attribute from highcharts.js?

I have a very simple highcharts js chart, which has dates on x-axis and values on y-axis. It works fine with this code:
chart = new Highcharts.Chart({
chart: {
renderTo: 'chart_container',
type: 'line',
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%e / %b'
}
},
yAxis: {
title: {
text: null
},
tickInterval: 1,
tickmarkPlacement: 'on',
min: 1,
max: 5
},
series: [{
name: 'serie_1',
pointInterval: 24 * 3600 * 1000, // one day
pointStart: Date.UTC(2011, 11, 22),
data: [
2, 3, 5, 4, null, 4, 4, 4, 4, 3, 2, 2, 1, 2, 2, null
]
}]
});
I also have an event that changes the chart's data when some action is triggered:
function reloadChart(){
$.get('/my/ajax/link/', { ajax_param: 10 },
function(data){
// HOW TO GET THIS TO WORKS??? series.pointStart is readonly
chart.series[0].pointStart = data.newPointStart;
chart.series[0].setData(data.data, true);
}
);
}
My question is: How can I update my series[0].pointStart after chart has been initialized?
I would rethink this. It would be easier to create an x,y points from your y-value series instead of using the pointStart and pointInterval options.
startDate = Date.UTC(2010, 0, 1);
createData = function(beginDate){
someData = [];
for (var i = 0; i < 11; i++){
someData.push([beginDate + (3600 * 1000 * 24 * i), Math.random() * 100]);
}
return someData;
}
....
series: [{
data: createData(startDate)
}]
Then in your function:
nextDay = function(){
startDate += 3600 * 1000 * 24;
chart.series[0].setData(createData(startDate), true);
}
Working fiddle here.
i think this is what you are looking for
chart.xAxis[0].setCategories();
see also the working jsFiddle

Categories