Plotly - starting X axis from first data point - javascript

In this plotly example,
The first date is on the first of January,
var trace1 = {
x: ['2000-01-01',
However, the first label shown on the graph is Jan 2.
Is there a way to force the graph to start from the 1st of January?

You have several possibilities to specify the first tick value of your x-axis.
Use tick0 together with dticks
var layout = {
xaxis: {
tick0: '2000-01-01',
dtick: 7*24*60*60*1000 // 7 days
};
or completely set the tickvals yourself
var layout = {
xaxis: {
tickvals: ['2000-01-01', '2000-01-15', '2000-01-31']
};
var trace1 = {
x: ['2000-01-01', '2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08', '2000-01-09', '2000-01-10', '2000-01-11', '2000-01-12', '2000-01-13', '2000-01-14', '2000-01-15', '2000-01-16', '2000-01-17', '2000-01-18', '2000-01-19', '2000-01-20', '2000-01-21', '2000-01-22', '2000-01-23', '2000-01-24', '2000-01-25', '2000-01-26', '2000-01-27', '2000-01-28', '2000-01-29', '2000-01-30', '2000-01-31'],
y: [4.3, 8.2, 4.1, 5.6, -3, -0.2, 0.3, 0.4, 4.1, 5, 4.6, -0.2, -8.5, -9.1, -2.7, -2.7, -17, -11.3, -5.5, -6.5, -16.9, -12, -6.1, -6.6, -7.9, -10.8, -14.8, -11, -4.4, -1.3, -1.1],
mode: 'lines',
type: 'scatter',
name: '2000'
};
var data = [trace1];
var layout = {
xaxis: {
type: 'date',
title: 'January Weather',
tick0: '2000-01-01',
dtick: 7 * 24 * 60 * 60 * 1000
},
yaxis: {
title: 'Daily Mean Temperature'
},
title:'2000 Toronto January Weather'
};
Plotly.plot('myDiv', data, layout);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="myDiv" style="width:100%;height:400px;"></div>

Related

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 - Use time for xAxes

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/

Highcharts - display dates in heatmap

I there any easy way to load the data in the heatmap with dates on "Y".
My data is in the following format:
[{x:1, y: 1401292253, value:0.2, name:"a"},{x:2, y: 1401173762, value:0.3, name:"b"},{x:0, y: 1401173462 , value:0.6, name:"c"}]
I want Y of the heatmap to be build automatically based on the given value. But I cant figure out how to do it.
What I've tried is:
http://jsfiddle.net/tZ6GP/16/
You need to set rowsize (or colsize for xAxis) to tell highcharts what is the range for each point. Otherwise it will be 1ms which is really low value. Second thing is that your y-values are in seconds, while in JS timestamps are in ms.
When changed that two things, you will get nice chart: http://jsfiddle.net/tZ6GP/19/
series: [{
rowsize: 3600000, // one hour
data: [{
x: 0,
y: 1401292253000,
value: 0.2,
name: "a"
}, {
x: 1,
y: 1401173762000,
value: 0.3,
name: "b"
}, {
x: 2,
y: 1401173462000,
value: 0.6,
name: "c"
}]
}]
To do this you have to treat your yAxis as categories still but then apply a label.format. This should get you started:
xAxis: {
type: 'category',
categories: ['a', 'b', 'c']
},
yAxis: {
type: 'category',
categories: ['1401292253', '1401173762', '1401173462'],
labels: {
format: '{value: %H:%M:%S}'
}
}
I also cleaned up your series.data a bit. Basically you need to give the matrix coordinates (x/y) and the value.
series: [{
data: [{
x: 1,
y: 0,
value: 0.2
}, {
x: 2,
y: 1,
value: 0.3
}, {
x: 0,
y: 2,
value: 0.6
}]
}]
By looking at this you can make out the locations of your points.
Live demo.
Update for latest highcarts code. You need to modify the yAxis label formatter:
yAxis: {
categories: ['1401292253', '1401173762', '1401173462'],
labels: {
formatter: function () {
var theTime = parseFloat(this.value);
return Highcharts.dateFormat('%H:%M:%S', theTime);
}
}
},
Update live demo.

HighCharts - timeseries chart - irregular datetime interval on xAxis

I need to make a chart on which xAxis is of type 'datetime', but have irregular intervals:
http://jsfiddle.net/cz6rL/
this is the code:
$(function () {
$('#chart1').highcharts({
chart: {
zoomType: 'x',
spacingRight: 20
},
title: {
text: 'Incomes/Outcomes'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' :
'Pinch the chart to zoom in'
},
xAxis: {
type: 'datetime',
minRange: 15 * 24 * 3600000,
title: {
text: null
}
},
yAxis: {
title: {
text: 'Euro(€)'
}
},
tooltip: {
shared: true
},
legend: {
enabled: true
},
plotOptions: {
area: {
fillColor: {
linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1},
stops: [
[0, Highcharts.getOptions().colors[9]],
[1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
]
},
//lineWidth: 1,
marker: {
enabled: false
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
},
threshold: null
}
},
series: [{
type: 'area',
pointInterval: 24 * 3600 * 1000,
pointStart: Date.UTC(2014, 0, 01),
data: [["31/12/2013", 345.2], ["09/01/2014", 494.79999999999995], ["20/01/2014", 137.2], ["22/01/2014", 210.0],
["23/01/2014", 220.4], ["24/01/2014", 871.0], ["28/01/2014", 420.0], ["30/01/2014", 420.0], ["31/01/2014", 2057.15],
["05/02/2014", 191.2], ["06/02/2014", 81.6], ["07/02/2014", 295.2], ["11/02/2014", 135.12], ["12/02/2014", 189.2],
["13/02/2014", 210.0], ["14/02/2014", 315.2], ["17/02/2014", 462.79999999999995], ["18/02/2014", 544.4],
["19/02/2014", 715.4399999999999], ["20/02/2014", 971.2], ["21/02/2014", 418.0], ["02/02/2015", 366.0]]
}]
});
});
you can see that series values do not correspond to xAxis values. How can I fix it: having same days on xAxis or having months corresponding to series values days?
thanks
Luke
You can remove the pointStart assignment, highcharts will determine the range based on trhe values you provide it. Highcharts will take a look at the range of data you supply it and auto generate the tick marks based on your tickInterval settings, and the available dimensions of your chart. If you need the tick marks on the axis to be specifically the dates you have in you data, you should not used the datetime type axis.
Highcharts handles all date data value in unix/epoch time (number of seconds since 1/1/1970). If you want to use datetime axis, you must supply your data in that format.
Change all your date values such as
["31/12/2013", 345.2]
to
[Date.UTC(2013, 11, 31), 345.2]

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