Date on H-Axis with log-scale (Google Chart) - javascript

I need a log-scale on H-Axis formatted as DATE.
In the example you can see the H-Axis (0-100) visualized as log-scale, no problem. I need this scale to be actual Dates. I know if you got 2 dates or 2 timestamps you cant just log between them.
Attempt
x (H-Axis) are the PAST_SECONDS so provided 0-100 in case i want to look back 100 seconds.
Problem
As soon as i use a non Date-Time value im not able to Format the PAST SECONDS to a well formatted Date. Formatting would go like: TIMESTAMP + PAST_SECONDS
Question
Is there a way to get a formatting callback or else for the H-Axis labels?
If not, is there a way to get the formatted date (from PAST_SECONDS) into the popup?
Example with PAST_SECONDS as H-Axis(x)
var chart_options = {
hAxis: {
logScale: true,
direction: -1,
},
vAxes: {
0: {
title: 'A',
viewWindowMode:'explicit',
viewWindow: {
max:100,
min:1
},
gridlines: {style: "dashed",},
},
1: {
title: 'B',
viewWindowMode:'explicit',
viewWindow: {
max:100,
min:1
},
gridlines: {color: 'transparent'},
},
},
series: {
0: {
type: 'line',
targetAxisIndex:0,
color: '#C0504E',
},
1: {
type: 'area',
targetAxisIndex:1,
color: '#4F81BC'
}
},
};
google.charts.load('current', {'packages':['corechart'], 'language': 'en'});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
chart = new google.visualization.ComboChart($('#chart').get(0));
chart_data = new google.visualization.DataTable();
chart_data.addColumn('number', 'x');
chart_data.addColumn('number', 'A');
chart_data.addColumn('number', 'B');
for( var i = 0; i < 100; i++ ) {
chart_data.addRow([
i,
Math.round(Math.random()*10)+70,
Math.round(Math.random()*20)+20
]);
}
chart.draw(chart_data, chart_options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

Related

Google Charts - Plot different things in different parts of the chart

So I'm currently building a financial chart with price information, account balance and an additional technical indicator, my current issue is that whilst displaying price information or account balance is fairly straight forward and non-obstructive, displaying the additional technical indicator puts it in the way of the other information as it is oscillating in value.
This is what I currently have but ideally I'd want the RSI to be at the bottom of the chart like so: (only the position of having the technical indicator at the bototm)
My current code to generate this
<script type="text/javascript">
google.charts.load('current', { packages: ['corechart', 'line'] });
google.charts.setOnLoadCallback(drawCurveTypes);
function drawCurveTypes() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Backtest');
data.addColumn('number', 'BTCUSDT');
data.addColumn({ 'type': 'string', 'role': 'style' })
data.addColumn('number', 'RSI');
data.addRows([date, balance, price, null, rsi]);
var options = {
hAxis: {
title: 'Time',
},
vAxes: {
// Adds titles to each axis.
0: { title: 'Price' },
1: { title: 'Backtest' },
2: { title: 'RSI'},
},
series: {
0: { targetAxisIndex: 0 },
1: { targetAxisIndex: 1 },
2: { targetAxisIndex: 2 }
},
explorer: {
axis: 'horizontal',
keepInBounds: true,
maxZoomIn: 20
},
colors: ['#6C91DB', 'black','orange'],
pointSize: 1,
dataOpacity: 0.7
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>

Cusomizing haxis label in google charts

I do have the following function to draw a chart, which represents some value for a given time. The horizontal axis should be the dates an not the numbers (which are important to make the trendline work). How can i achieved that?
chart_data contains of the following
[["Year","accept","error","total"],[{"v":0,"f":"20.09.2018"},1,3,4],
[{"v":1,"f":"21.09.2018"},4,5,9],[{"v":2,"f":"22.09.2018"},0,7,7],
[{"v":3,"f":"24.09.2018"},14,14,28],[{"v":4,"f":"25.09.2018"},2,2,4],
[{"v":5,"f":"26.09.2018"},6,16,22]]
The js function looks like this:
function drawChart(chart_id, chart_title, chart_data) {
var data = google.visualization.arrayToDataTable(
chart_data
);
var options = {
title: chart_title,
hAxis: {
title: 'Datum',
titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0},
trendlines: {
0: {
type: 'polynomial',
degree: 3,
},
1:{
type: 'polynomial',
degree: 3,
},
2:{
type: 'polynomial',
degree: 3,
} } // Draw a trendline for data series 0.
};
var chart = new google.visualization.AreaChart(document.getElementById(chart_id));
chart.draw(data, options);
}
to customize the haxis labels, use option hAxis.ticks
in this case, we can pull the first value from each row to use for our ticks
var chart_data = [
["Year","accept","error","total"],
[{"v":0,"f":"20.09.2018"},1,3,4],
[{"v":1,"f":"21.09.2018"},4,5,9],
[{"v":2,"f":"22.09.2018"},0,7,7],
[{"v":3,"f":"24.09.2018"},14,14,28],
[{"v":4,"f":"25.09.2018"},2,2,4],
[{"v":5,"f":"26.09.2018"},6,16,22]
];
// extract first value from each row
var ticks = chart_data.map(function (row) {
return row[0];
});
ticks.splice(0, 1); // remove column label
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var chart_data = [
["Year","accept","error","total"],
[{"v":0,"f":"20.09.2018"},1,3,4],
[{"v":1,"f":"21.09.2018"},4,5,9],
[{"v":2,"f":"22.09.2018"},0,7,7],
[{"v":3,"f":"24.09.2018"},14,14,28],
[{"v":4,"f":"25.09.2018"},2,2,4],
[{"v":5,"f":"26.09.2018"},6,16,22]
];
// extract first value from each row
var ticks = chart_data.map(function (row) {
return row[0];
});
ticks.splice(0, 1); // remove column label
var data = google.visualization.arrayToDataTable(chart_data);
var options = {
title: 'chart_title',
hAxis: {
ticks: ticks, // custom labels
title: 'Datum',
titleTextStyle: {color: '#333'}
},
vAxis: {minValue: 0},
trendlines: {
0: {
type: 'polynomial',
degree: 3,
},
1:{
type: 'polynomial',
degree: 3,
},
2:{
type: 'polynomial',
degree: 3,
}
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Not able to zoom in on Google Charts

I have created a Google Chart that visualises the outside temperature at my house. The amount of data keeps growing, so the chart gets unreadable in a few days ;-)
I want to be able to zoom in on the x-axis, but I can't get it to work with the explorer option.
I've tried:
explorer: { actions: ["dragToZoom", "rightClickToReset"],
maxZoomIn: 0.2,
maxZoomOut: 1.0,
zoomDelta: 10,
axis: "horizontal",
keepInBounds: true
},
But that doesn't seem to work.
Here's what I've got so far:
https://codepen.io/wtrdk/pen/wpGVVW or https://weather.wtrdk.nl/test.html
UPDATE:
I've added the following code to create a continuous axis, but I still can't zoom in...
var view = new google.visualization.DataView(data);
view.setColumns([
// first column is calculated
{
calc: function (dt, row) {
// convert string to date
return new Date(dt.getValue(row, 0));
},
label: data.getColumnLabel(0),
type: 'datetime'
},
// just use index # for second column
1
]);
try using the current library...
<script src="https://www.gstatic.com/charts/loader.js"></script>
jsapi is out of date, according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on.
this will only change the load statement,
see following working snippet...
google.charts.load('current', {
packages: ['corechart', 'controls']
}).then(function () {
$.get(
"https://cors-anywhere.herokuapp.com/https://weather.wtrdk.nl/temperature.csv",
function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {
onParseValue: $.csv.hooks.castToScalar
});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
var view = new google.visualization.DataView(data);
view.setColumns([
// first column is calculated
{
calc: function (dt, row) {
// convert string to date
return new Date(dt.getValue(row, 0));
},
label: data.getColumnLabel(0),
type: 'datetime'
},
// just use index # for second column
1
]);
var temperature = new google.visualization.ChartWrapper({
chartType: "AreaChart",
containerId: "temperature",
dataTable: view,
options: {
height: 400,
explorer: {
actions: ["dragToZoom", "rightClickToReset"],
//axis: "horizontal",
//keepInBounds: true
},
animation: { duration: 2000, easing: "out", startup: true },
title: "Temperature",
titleTextStyle: { color: "grey", fontSize: 11 },
legend: { textStyle: { color: "grey", fontSize: 11 } },
backgroundColor: { fill: "transparent" },
colors: ["#e39c3a"],
hAxis: {
textStyle: {
color: "grey",
fontSize: 11
},
//format: 'datetime',
},
vAxis: {
title: "°C",
titleTextStyle: {
color: "grey",
fontSize: 22
},
textStyle: {
color: "grey",
fontSize: 11
}
}
}
});
temperature.draw();
}
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://weather.wtrdk.nl/jquery.csv.min.js"></script>
<body bgcolor="#282B30">
<div id="temperature"></div>
</body>

Handling null data on Google Charts

I'm trying to create compound chart with a given data, that is, [date, value1, value2], however I can not handle such inputs:
// [["Day","Dose","INR"],["17/04",1.5,null]]
// [["Day","Dose","INR"]]
// [["Day","Dose","INR"],["17/04",1.5,null],["18/04",2.5,null]]
that is, when there are a set of data with a particular value all consist of nulls, I can not draw it on graph. Such inputs are fine:
// [["Day","Dose","INR"],["17/04",1.5,null],["18/04",2.5,0.9]]
// [["Day","Dose","INR"],["17/04",1.5,null],["18/04",2.5,0.9],["19/04",null,1.4]]
And here is my javascript code drawing the graph. Data is coming from a Ruby model.
$(function () {
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable(<%= DrugInr.generate_array(#patient) %>);
var options = {
vAxes: { 1: {title: 'Dose', format: '#.#', maxValue: 20},
0: {title: 'INR',format: '#.#', minValue: -1, baselineColor:"#CCCCCC"} },
hAxis: {title: 'Day'},
seriesType: 'bars',
bar: {
groupWidth: 2
},
series: {
0:{ type: "bars", targetAxisIndex: 1 },
1:{ type: 'line', targetAxisIndex: 0}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
});
How can I handle these half empty values?
I would recommend the interpolateNulls option. See the ComboChart Configuration Options documentation for details.
var options = {
interpolateNulls: true
};
This option just tells the chart to guess what your values are if there's a null, rather than leave a gap. Works for most cases, anyway.
I solved this creating my data table like this:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'INR');
data.addColumn('number', 'Dosage');
data.addRows(<%= DrugInr.generate_array(#patient) %>);
var options = {
vAxes: { 1: {title: 'Dose', format: '#.#', maxValue: 20},
0: {title: 'INR',format: '#.#', minValue: -1, baselineColor:"#CCCCCC"} },
hAxis: {title: 'Day'},
seriesType: 'bars',
bar: {
groupWidth: 5
},
series: {
0:{ type: "bars", targetAxisIndex: 1 },
1:{ type: 'line', targetAxisIndex: 0}
}
};

Correctly plot time series in Highcharts/Highstock

I have large collection of data in the format [1421065200000, 1.72], where the first parameter is time in milliseconds and the second parameter is the value at that specific time. I have data array consisting of such data in large size. Now I want scrollable graph containing plot of such time and value data. Here is my javascript implementation to do so,
var dataArray; //This contains my data array i.e. ([[t1, v1],[t2, v2],...])
var minDate = dataArray[0][0];
var maxDate = dataArray[dataArray.length - 1][0];
var chartOption = {
chart: {
type: graphType,
renderTo: 'graph-container',
zoomType: 'x',
useUTC: false
},
title: {
text: 'Data from last 24 hours'
},
credits : {
enabled: false
},
xAxis: {
title: {
text: null
},
type: 'datetime',
dateTimeLabelFormats: {
second: '%Y-%m-%d<br/>%H:%M:%S',
minute: '%Y-%m-%d<br/>%H:%M',
hour: '%Y-%m-%d<br/>%H:%M',
day: '%Y<br/>%m-%d',
week: '%Y<br/>%m-%d',
month: '%Y-%m',
year: '%Y'
},
allowDecimals: false,
ordinal: false,
min: minDate,
max: maxDate
},
yAxis: {
title: {
text: null
}
},
plotOptions: {
series: {
pointStart: minDate,
pointInterval: 5 * 60 *1000
}
},
series: [{
name: parameterName,
data: dataArray
}],
exporting: {
enabled: false
}
};
parameterChart = new Highcharts.Chart(chartOption);
}
The chart shows incorrect data, the time value on x-axis doesn't match the value at y-axis. What is the most correct and efficient to show such time series. Should I use Highcharts or Highstock. Please guide me through this, with suggestion or maybe with solution.
What I did was, I used HighStock instead of HighCharts (since I needed scrollbar along x-axis for large collection of data). I was passing the date in my local time zone format, whereas the chart was using UTC. So, I disabled the use of UTC (alternative: I could have provided data in UTC and drawn the graph using the same, In my case I needed my local labels). I gave the minimum and maximum range to the x-axis through x-axis min and max configuration. Here is the sample of my code,
//dataArray contains the array of data [[x1, y1], [x2, y2], ...]
//x is Date, y is temperature value (say)
var minDate = dataArray[0][0];
var maxDate = dataArray[dataArray.length - 1][0];
//Disable use of UTC
Highcharts.setOptions({
global: {
useUTC: false
}
});
//Create graph options
var chartOption = {
chart: {
type: graphType, //line, bar, column, etc
renderTo: 'graph-container', //div where my graph will be drawn
zoomType: 'x' //Making x-axis zoomable/scrollable
},
title: {
text: 'Data from last 6 hours'
},
subtitle: {
text: document.ontouchstart === undefined ?
'Click and drag in the plot area to zoom in' :
'Pinch the chart to zoom in'
},
xAxis: {
title: {
text: null
},
type: 'datetime', //For time series, x-axis labels will be time
labels: {
//You can format the label according to your need
format: '{value:%H:%m}'
},
min: minDate,
max: maxDate,
minPadding: 0.05,
maxPadding: 0.05
},
yAxis: {
title: {
text: null
}
},
scrollbar: {
enabled: true
},
series: [{
name: "Temperature", //Name of the series
data: dataArray
}],
exporting: {
enabled: false
},
credits : {
enabled: false
}
};
//Finally create the graph
var myChart = new Highcharts.Chart(chartOption);

Categories

Resources