Handling null data on Google Charts - javascript

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}
}
};

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>

Set slanted text for Google Charts (Material Bar chart)

Have tried the following:
hAxis: {slantedText: true, slantedTextAngle: 90}
However this only works for core charts
I once needed to set the title on the material chart and used this work around:
series: {
0: {targetAxisIndex: 0},
},
vAxes: {
// Adds titles to each axis.
0: {title: '# of Successes'},
},
Wondering if the solution involves manipulating the code above
var options = {
title: 'Nombre d emails par jour',
hAxis: {title: 'Jour', titleTextStyle: {color: '#333'}, slantedText: true},
vAxis: {minValue: 0},
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);

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

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>

How to make bars of different color in google charts?

I have the following code which generates a column chart.
<script type="text/javascript">
//google.charts.load('current', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(drawBar);
function drawBar() {
var data = google.visualization.arrayToDataTable([
['Number of Visits', 'Average Check Size',{ role: 'style' }],
['8+', 26.22, '#083874'],
['4-7', 30.34,'#94CAFC'],
['2-3', 24.09,'#EBBA25'],
['1', 27.95,'#F59E47']
]);
var formatter = new google.visualization.NumberFormat({
fractionDigits: 1,
prefix: '$'
});
formatter.format(data, 1);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" }]);
var options = {
//chartArea: {width: '50%'},
hAxis: {
title: 'Average Check Size',
titleTextStyle: {italic: false},
minValue: 0,gridlines: { color: 'transparent'}
},
vAxis: {
minValue: 0,
title: 'Number of Visits',
titleTextStyle: {italic: false},
gridlines: { color: 'transparent'}},
//colors: ['red','green','blue','yellow'],
legend: {position: 'none'},
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_bar'));
chart.draw(view, options);
}
The output is a column chart with annotations on each of the bars. I want to have a similar kind of output but all four bars must have different colors. How do I do that? Please suggest
You can use the style role. There are examples on google charts page. And here is a jsfiddle.
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }],
['Copper', 8.94, '#b87333'], // RGB value
['Silver', 10.49, 'silver'], // English color name
['Gold', 19.30, 'gold'],
['Platinum', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
]);

Categories

Resources