haxis text doesn't show all records and can't be slanted - google-visualization

I use Google Charts to show a stacked bar chart (two bars per year).
The data displays just fine but the haxis (years) should be slanted (i.e. 30 degrees) and should display more than every fifth year.
Any suggestion is more than welcome. Thanks!
Picture is in my dropbox. https://www.dropbox.com/s/niru4cyw8x4m98m/stack.png?dl=0
"data:text/html;charset=UTF-8,<html> <head>
<script type=\"text/javascript\" src=\"https://www.gstatic.com/charts/loader.js\"></script>
<script type=\"text/javascript\">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['', 'Investiertes Vermögen', 'Kumulierter Gewinn/Verlust'],
[" & InvestKapital::Jahr01a & ", " & InvestKapital::InvestKapital01a & "," & InvestKapital::KumErfolg01a & "],
[" & InvestKapital::Jahr01b & ", " & InvestKapital::InvestKapital01b & "," & InvestKapital::KumErfolg01b & "],
[" & InvestKapital::Jahr02a & ", " & InvestKapital::InvestKapital02a & "," & InvestKapital::KumErfolg02a & "],
[" & InvestKapital::Jahr02a & ", " & InvestKapital::InvestKapital02b & "," & InvestKapital::KumErfolg02b & "],
[" & InvestKapital::Jahr03a & ", " & InvestKapital::InvestKapital03a & "," & InvestKapital::KumErfolg03a & "],
[" & InvestKapital::Jahr03a & ", " & InvestKapital::InvestKapital03b & "," & InvestKapital::KumErfolg03b & "],
[" & InvestKapital::Jahr04a & ", " & InvestKapital::InvestKapital04a & "," & InvestKapital::KumErfolg04a & "],
[" & InvestKapital::Jahr04a & ", " & InvestKapital::InvestKapital04b & "," & InvestKapital::KumErfolg04b & "],
[" & InvestKapital::Jahr05a & ", " & InvestKapital::InvestKapital05a & "," & InvestKapital::KumErfolg05a & "],
[" & InvestKapital::Jahr05a & ", " & InvestKapital::InvestKapital05b & "," & InvestKapital::KumErfolg05b & "],
[" & InvestKapital::Jahr06a & ", " & InvestKapital::InvestKapital06a & "," & InvestKapital::KumErfolg06a & "],
[" & InvestKapital::Jahr06a & ", " & InvestKapital::InvestKapital06b & "," & InvestKapital::KumErfolg06b & "],
[" & InvestKapital::Jahr07a & ", "& InvestKapital::InvestKapital07a & "," & InvestKapital::KumErfolg07a & "],
[" & InvestKapital::Jahr07a & ", " & InvestKapital::InvestKapital07b & "," & InvestKapital::KumErfolg07b & "],
[" & InvestKapital::Jahr08a & ", " & InvestKapital::InvestKapital08a & "," & InvestKapital::KumErfolg08a & "],
[" & InvestKapital::Jahr08b & ", " & InvestKapital::InvestKapital08b & "," & InvestKapital::KumErfolg08b & "],
[" & InvestKapital::Jahr09a & ", "& InvestKapital::InvestKapital09a & "," & InvestKapital::KumErfolg09a & "],
[" & InvestKapital::Jahr09a & ", " & InvestKapital::InvestKapital09b & "," & InvestKapital::KumErfolg09b & "],
[" & InvestKapital::Jahr10a & ", " & InvestKapital::InvestKapital10a & "," & InvestKapital::KumErfolg10a & "],
[" & InvestKapital::Jahr10b & ", " & InvestKapital::InvestKapital10b & "," & InvestKapital::KumErfolg10b & "]
], false);
var options = {
isStacked: true,
tooltip: {
textStyle: {color: '#000000', fontName: 'Mrs Eaves XL Serif OT', fontSize: 9},
},
legend: {position: 'none', textStyle: {color: '#000000', fontSize: 9}
},
vAxis: {minValue: 0,
textStyle: {color: '#000000', fontName: 'Mrs Eaves XL Serif OT', fontSize: 10},
},
hAxis: {format: '',
textStyle: {color: '#000000', fontName: 'Mrs Eaves XL Serif OT', fontSize: 9},
slantedText: true,
maxAlternation: 1, // use a maximum of 1 line of labels
showTextEvery: 1, // show every label if possible
minTextSpacing: 1, // minimum spacing between adjacent labels, in pixels
},
series: {
0:{color:'#0A5550'},
1:{color:'#8C8C91'},
},
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));}
</script> </head> <body>
<div id=\"columnchart_material\" style=\"width: 350px; height: 190px;\"></div>
</body> </html>"

Related

Highcharts tooltip formatter function does not display values in table correct

I have created an if else statement in my highcharts tooltip formatter function in order to display y values from different point.series.name.
Values from first and second series in the array displays correct, but styling for the last series.name values (HINDCAST - SPREAD) does not display correct, because font-size and point.series.color does not show. I suppose the problem is the table tags? Please see fiddle
https://jsfiddle.net/marialaustsen/w4k87jyo/
tooltip: {
shared: true,
useHTML: true,
formatter: function() {
var aYearFromNow = new Date(this.x);
aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 5);
var tooltip = '<table><span style="font-size: 16px">' +
Highcharts.dateFormat('%e/%b/%Y', new Date(this.x)) + '-' + Highcharts.dateFormat('%e/%b/%Y', aYearFromNow) + '</span><br/><tbody>';
//loop each point in this.points
$.each(this.points, function(i, point) {
if (point.series.name === 'Observations') {
tooltip += '<tr><th style="font-size: 14px; color: ' + point.series.color + '">' + point.series.name + ': </th>' +
'<td style="font-size: 14px">' + point.y + '℃' + '</td></tr>'
} else if (point.series.name === 'BOXPLOT') {
const x = this.x;
const currentData = this.series.data.find(data => data.x === x);
const boxplotValues = currentData ? currentData.options : {};
tooltip += `<span style="font-size: 14px; color: #aaeeee">
Max: ${boxplotValues.high.toFixed(2)}<br>
Q3: ${boxplotValues.q3.toFixed(2)}<br>
Median: ${boxplotValues.median.toFixed(2)}<br>
Q1: ${boxplotValues.q1.toFixed(2)}<br>
Low: ${boxplotValues.low.toFixed(2)}<br></span>`;
} else {
tooltip += '<tr><th style="font-size: 14px; color: ' + point.series.color + '">' + point.series.name + ': </th>' +
'<td style="font-size: 14px">' + point.point.low + '℃ -' + point.point.high + '℃' + '</td></tr>' +
'</tbody></table>';
}
});
return tooltip;
}
},
You're closing the tbody before the last value (HINDCAST - SPREAD), once put outside the for loop it works :
...
tooltip += '<tr><th style="font-size: 14px; color: ' + point.series.color + '">' + point.series.name + ': </th>' +
'<td style="font-size: 14px">' + point.point.low + '℃ -' + point.point.high + '℃' + '</td></tr>'
}
});
tooltip += '</tbody></table>';
return tooltip;
...
Fiddle

Chart.js 2.0: How to dispplay tooltip while Mouse flyover

I have a problem with the display of the tooltips when hovering over a mouse in my graph in Chart.js. When the screen is small it is displayed and when I go back to normal size it is displayed more.
here is my code:
if ((window.screen.width > 375) && (window.screen.height > 568)) {
$scope.billing_options = {
//responsive: true,
legend: {
display: true
},
scales: {
yAxes: [{
//axe des y
ticks: {
beginAtZero: true,
suggestedMax: 0.07,
//Create % notation labels
callback: function (value, index, values) {
return Math.round((value) * 100) + " %";
}
}
}]
},
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
if (data.datasets[tooltipItem.datasetIndex].label == 'Avenant') {
return data.datasets[tooltipItem.datasetIndex].label + ': ' + ((factudata[tooltipItem.index].salesVariation)) + " %";
} else
return data.datasets[tooltipItem.datasetIndex].label + ': ' + ((data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index])) + " %";
}
}
}
};

Grid lines on google charts are not rendering as per data

Link to jsFiddle
google.charts.load('current', {
'packages': ['corechart']
});
//Input data
var data = [
['Data', 'CAT1', 'CAT2', 'CAT3', 'CAT4'],
['Provisions', 5, 0, 0, 0],
];
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var options = {
colors: ['#00699B', '#087EB4', '#CBE7F7', '8A6996'],
isStacked: true,
chartArea: {
width: '40%'
},
bar: {
groupWidth: "40%"
},
// tooltip: { isHtml: true },
trigger: 'both',
vAxis: {
gridlines: {
color: '#0000006b',
minValue: 0,
baseline: 0
},
format: "$ #,###"
},
};
var dataTable = google.visualization.arrayToDataTable(data);
//Formatters
var intergerFormatter = new google.visualization.NumberFormat({
groupingSymbol: ",",
fractionDigits: 0
});
for (var i = 0; i < data[0].length; i++) {
intergerFormatter.format(dataTable, i);
}
var view = new google.visualization.DataView(dataTable);
var cols =   [0];
for (var i = 1; i < data[0].length; i++) {
cols.push({
sourceColumn: i,
type: "number",
label: data[0][i]
});
cols.push({
calc: createTooltip(i),
type: "string",
role: "tooltip",
});
}
view.setColumns(cols);
var chart = new google.visualization.ColumnChart(document.getElementById('provision_chart'));
chart.draw(view, options);
function createTooltip(col) {
return function(dataTable, row) {
var html = dataTable.getColumnLabel(col) + ":" + "\n";
html += "4 " + dataTable.getValue(row, 0) + "\n";
html += "$ " + intergerFormatter.formatValue(dataTable.getValue(row, col)) + " total" + "\n";
return html;
};
}
}
The grid lines on a stacked bar type google charts are not rendering properly.
As per the data, $5 is recorded against Category1, but when it's rendered the bar is slightly over $5.
Can someone suggest a fix?
removing the option --> format: "$ #,###" -- reveals the problem
although the tick mark displays --> $ 5 -- the actual number used is 4.5
see following working snippet...
google.charts.load('current', {
'packages': ['corechart']
});
//Input data
var data = [
['Data', 'CAT1', 'CAT2', 'CAT3', 'CAT4'],
['Provisions', 5, 0, 0, 0],
];
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var options = {
colors: ['#00699B', '#087EB4', '#CBE7F7', '8A6996'],
isStacked: true,
chartArea: {
width: '40%'
},
bar: {
groupWidth: "40%"
},
// tooltip: { isHtml: true },
trigger: 'both',
vAxis: {
gridlines: {
color: '#0000006b',
minValue: 0,
baseline: 0
},
//format: "$ #,###"
},
};
var dataTable = google.visualization.arrayToDataTable(data);
//Formatters
var intergerFormatter = new google.visualization.NumberFormat({
groupingSymbol: ",",
fractionDigits: 0
});
for (var i = 0; i < data[0].length; i++) {
intergerFormatter.format(dataTable, i);
}
var view = new google.visualization.DataView(dataTable);
var cols =   [0];
for (var i = 1; i < data[0].length; i++) {
cols.push({
sourceColumn: i,
type: "number",
label: data[0][i]
});
cols.push({
calc: createTooltip(i),
type: "string",
role: "tooltip",
});
}
view.setColumns(cols);
var chart = new google.visualization.ColumnChart(document.getElementById('provision_chart'));
chart.draw(view, options);
function createTooltip(col) {
return function(dataTable, row) {
var html = dataTable.getColumnLabel(col) + ":" + "\n";
html += "4 " + dataTable.getValue(row, 0) + "\n";
html += "$ " + intergerFormatter.formatValue(dataTable.getValue(row, col)) + " total" + "\n";
return html;
};
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="provision_chart" style="width: 500px; height: 500px;"></div>
to correct, you can add a decimal place to the format --> $ #,##0.0
or provide your own vAxis.ticks in an array --> [0, 1, 2, 3, 4, 5, 6]
see following working snippet...
google.charts.load('current', {
'packages': ['corechart']
});
//Input data
var data = [
['Data', 'CAT1', 'CAT2', 'CAT3', 'CAT4'],
['Provisions', 5, 0, 0, 0],
];
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var options = {
colors: ['#00699B', '#087EB4', '#CBE7F7', '8A6996'],
isStacked: true,
chartArea: {
width: '40%'
},
bar: {
groupWidth: "40%"
},
// tooltip: { isHtml: true },
trigger: 'both',
vAxis: {
gridlines: {
color: '#0000006b',
minValue: 0,
baseline: 0
},
format: "$ #,###",
ticks: [0, 1, 2, 3, 4, 5, 6]
},
};
var dataTable = google.visualization.arrayToDataTable(data);
//Formatters
var intergerFormatter = new google.visualization.NumberFormat({
groupingSymbol: ",",
fractionDigits: 0
});
for (var i = 0; i < data[0].length; i++) {
intergerFormatter.format(dataTable, i);
}
var view = new google.visualization.DataView(dataTable);
var cols =   [0];
for (var i = 1; i < data[0].length; i++) {
cols.push({
sourceColumn: i,
type: "number",
label: data[0][i]
});
cols.push({
calc: createTooltip(i),
type: "string",
role: "tooltip",
});
}
view.setColumns(cols);
var chart = new google.visualization.ColumnChart(document.getElementById('provision_chart'));
chart.draw(view, options);
function createTooltip(col) {
return function(dataTable, row) {
var html = dataTable.getColumnLabel(col) + ":" + "\n";
html += "4 " + dataTable.getValue(row, 0) + "\n";
html += "$ " + intergerFormatter.formatValue(dataTable.getValue(row, col)) + " total" + "\n";
return html;
};
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="provision_chart" style="width: 500px; height: 500px;"></div>
the getColumnRange(colIndex) method can assist in building the ticks dynamically
the method returns an object {} with properties for min and max for the column index provided
see following working snippet for an example...
google.charts.load('current', {
'packages': ['corechart']
});
//Input data
var data = [
['Data', 'CAT1', 'CAT2', 'CAT3', 'CAT4'],
['Provisions', 5, 0, 0, 0],
];
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var options = {
colors: ['#00699B', '#087EB4', '#CBE7F7', '8A6996'],
isStacked: true,
chartArea: {
width: '40%'
},
bar: {
groupWidth: "40%"
},
// tooltip: { isHtml: true },
trigger: 'both',
vAxis: {
gridlines: {
color: '#0000006b',
minValue: 0,
baseline: 0
},
format: "$ #,###"
},
};
var dataTable = google.visualization.arrayToDataTable(data);
//Formatters
var intergerFormatter = new google.visualization.NumberFormat({
groupingSymbol: ",",
fractionDigits: 0
});
for (var i = 0; i < data[0].length; i++) {
intergerFormatter.format(dataTable, i);
}
var view = new google.visualization.DataView(dataTable);
var cols = [0];
var ticksY = [];
var maxY = null;
var minY = null;
for (var i = 1; i < view.getNumberOfColumns(); i++) {
var range = view.getColumnRange(i);
if (maxY === null) {
maxY = Math.ceil(range.max);
} else {
maxY = Math.max(maxY, Math.ceil(range.max));
}
if (minY === null) {
minY = Math.floor(range.min);
} else {
minY = Math.min(minY, Math.floor(range.min));
}
}
for (var i = minY; i <= maxY + 1; i++) {
ticksY.push(i);
}
options.vAxis.ticks = ticksY;
for (var i = 1; i < data[0].length; i++) {
cols.push({
sourceColumn: i,
type: "number",
label: data[0][i]
});
cols.push({
calc: createTooltip(i),
type: "string",
role: "tooltip",
});
}
view.setColumns(cols);
var chart = new google.visualization.ColumnChart(document.getElementById('provision_chart'));
chart.draw(view, options);
function createTooltip(col) {
return function(dataTable, row) {
var html = dataTable.getColumnLabel(col) + ":" + "\n";
html += "4 " + dataTable.getValue(row, 0) + "\n";
html += "$ " + intergerFormatter.formatValue(dataTable.getValue(row, col)) + " total" + "\n";
return html;
};
}
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="provision_chart" style="width: 500px; height: 500px;"></div>

Google Charts, Html tooltips don't appear on bar chart

I created a bar chart, with an html tooltip that displayed an image. This worked perfectly. I then added event handlers for the Ready and Select events and a bootstrap modal that pops up when the user clicks on one of the bars. Now the html tooltips don't appear any more when you hover over a bar. But, if I change the code to say "tooltip: {}", then I do get the tooltip showing the html content (as text). I'm not sure if this is as a result of adding the event handlers, or adding bootstrap, but I can't get the tooltips to show an image any more.
How can I get the tooltips to show again? and how can I get them to show when I hover over the annotation on the bar? I thought that was what annotationText was for, but my (text) tooltip only shows when I hover over the bar, not the text.
Here is a cut down version of the code with irrelevant bits omitted for clarity:
var DashboardWindow = new function()
{
this.DetailChart = null;
this.onLoad = function()
{
google.charts.load( 'current', { 'packages': ['corechart', 'bar'] } );
google.charts.setOnLoadCallback( this.drawCharts );
j$( '#detailsPopup' ).on( 'show.bs.modal', DashboardWindow.getDetailsData );
}
this.detailsReadyHandler = function()
{
google.visualization.events.addListener( DashboardWindow.DetailChart, 'select', DashboardWindow.detailsSelectHandler );
}
this.detailsSelectHandler = function( e )
{
var selection = DashboardWindow.DetailChart.getSelection();
if( selection.length > 0 )
{
var item = DashboardWindow.DetailChartData.getValue( selection[0].row, 0 );
j$( '#detailsPopupTitle' ).text( item );
j$( '#detailsPopup' ).modal( { show: true, keyboard: true } );
}
}
this.drawCharts = function()
{
.....
j$.ajax( {
type: "POST",
url: .....
} ).done( function( result )
{
if( result.d.Detail != null )
{
var data = new google.visualization.DataTable();
var groupHeader = j$( '#' + Dashboard_DetailsType ).val();
data.addColumn( 'string', groupHeader );
data.addColumn( 'number', 'NPS Score' );
data.addColumn( { type: 'string', role: 'annotation' } );
data.addColumn( { type: 'string', role: 'style' } );
data.addColumn( { type: 'string', role: 'tooltip', p: { 'html': true } } );
data.addColumn( { type: 'string', role: 'annotationText', p: { 'html': true } } );
result.d.Detail.forEach( function( row )
{
var red = ....
var green = ....
var tooltip = '';
if( row.NPS != null )
{
tooltip = '<div class="tooltip"><b>' + row.GroupName + '</b><br/><hr/>NPS Score: <b>' + row.NPS.toFixed( 1 ) + '</b><br/>Responses: ' + row.NPSMessageCount.toString() + '<br>'
+ 'Last Score: ' + ( row.LastNPS == null ? 'none' : row.LastNPS.toFixed( 1 ) ) + '<br/>'
+ '<img id="overall_nps_score_trend" alt="trend" src="images/icons/trend-' + ( ( row.Trend == 1 ) ? 'up' : ( ( row.Trend == 255 ) ? 'down' : 'same' ) ) + '-64.png" /></div>';
}
data.addRow( [
row.GroupName,
row.NPS,
row.NPS == null ? '' : row.NPS.toFixed( 1 ) + ' (' + row.NPSMessageCount.toString() + ' Responses)',
row.NPS == null ? '' : 'color: #' + red + green + '50',
tooltip,
tooltip
] );
} );
var chartWidth = j$( '#nps_details_chart' ).width() - 300;
var options =
{
bar: { groupWidth: "90%" },
legend: { position: "none" },
hAxis: { minValue: 0, maxValue: 100 },
chartArea: { left: 260, top: 20, width: chartWidth, height: result.d.Detail.length * 34 - 80 },
height: result.d.Detail.length * 34,
tooltip: { isHtml: true, ignoreBounds: true, trigger: focus }
};
DashboardWindow.DetailChartData = data;
DashboardWindow.DetailChart = new google.visualization.BarChart( document.getElementById( "nps_details_chart" ) );
google.visualization.events.addListener( DashboardWindow.DetailChart, 'ready', DashboardWindow.detailsReadyHandler );
DashboardWindow.DetailChart.draw( data, options );
}
} )
.fail( function( response, status, error )
{
....
} );
}
}
function pageLoad()
{
DashboardWindow.onLoad();
}
For anyone else with a similar issue, there were 2 problems here.
The first was my use of 'div class="tooltip"' in my tooltip content, as bootstrap.css defines a tooltip class which seems to prevent the tootip being displayed. Changing the class name fixed the issue.
The second problem was tooltips not appearing over the annotation text. This is most noticable when the bar length is zero as there is no way to see the tootip. This code demonstrates the issue:
<html>
<body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
["District", "Score", { role: "annotation" }, { role: "tooltip", p: { html: true } } , { role: "annotationText", p: { html: true } }],
["District 1", 25, "12 (6 Responses)", "<b>Score 12</b><br/>(6 Responses)", "<b>Score 12</b><br/>(6 Responses)"],
["District 2", 5, "5 (8 Responses)", "<b>Score 5</b><br/>(8 Responses)", "<b>Score 5</b><br/>(8 Responses)"],
["District 3", 3, "3 (14 Responses)", "<b>Score 3</b><br/>(14 Responses)", "<b>Score 3</b><br/>(14 Responses)"],
["District 4", 0, "0 (3 Responses)", "<b>Score 0</b><br/>(3 Responses)", "<b>Score 0</b><br/>(3 Responses)"],
["District 5", 18, "18 (9 Responses)", "<b>Score 18</b><br/>(9 Responses)", "<b>Score 18</b><br/>(9 Responses)"],
]);
var options = {
title: "District Scores",
width: 600,
height: 400,
bar: {groupWidth: "95%"},
tooltip: { isHtml: true },
legend: { position: "none" },
};
var chart = new google.visualization.BarChart(document.getElementById("barchart_values"));
chart.draw(data, options);
}
</script>
<div id="barchart_values" style="width: 900px; height: 300px;"></div>
</body>
</html>
swapping the order of the tooltip and annotationText within the data fixes the issue. (i.e. make the annotationText the 4th column following the annotation).
I still can't get a tooltip over the annotation when the annotation is within the bar, but if the bar is short so that the annotation is outside of the bar then the tooltip is displaying ok.

Updating chart.js based on selections from dropdown

I have a calculator that takes values from two drop downs and runs them through an array to calculate odds in which a certain condition will end. I got it working and I show the results in a text format. My boss now wants me to show the results in a bar graph. I chose to use chart.js and can get the chart working with entering actual data into the chart, but need to have the data be pulled from the results of the selected drop downs.
For some reason the calculator in jsfiddle its not working correctly but does on my site. Not sure why.
Below I have the script that I use for the chart.js
<script src="js/Chart.js"></script>
<script src="js/Chart.HorizontalBar.js"></script>
<script src="js/Chart.StackedBar.js"></script>
<script>
var barData = {
labels : ["50% Probability","80% Probability","95% Probability","99% Probability"],
datasets : [
{
label: "Birth No Condition",
fillColor : "#137fc1",
strokeColor : "#137fc1",
data : [0,5,10,15]
},
{
label: "Current Age",
fillColor : "#ff0000",
strokeColor : "#ff0000",
data : [0,5,10,15]
}
]
}
var myChart = document.getElementById("myChart").getContext("2d");
new Chart(myChart).StackedBar(barData, {
scaleShowLabels: true,
responsive: true
});
</script>
I need to load in the data from the dropdowns into each of the datasets data so instead of it saying
datasets : [
{
label: "Birth No Condition",
fillColor : "#137fc1",
strokeColor : "#137fc1",
data : [0,5,10,15]
},
It would say
datasets : [
{
label: "Birth No Condition",
fillColor : "#137fc1",
strokeColor : "#137fc1",
data : colicWeeks
},
datasets : [
{
label: "Birth No Condition",
fillColor : "#137fc1",
strokeColor : "#137fc1",
data : finalAge50
},
I guess what I am trying to say is how do you push data from the results of each dropdown selection run it through the array and spit the results out into the chart.js bar graph?
Just update the latter part of your script (you should be able to locate where you need to paste it in based on the 1st line below)
...
if (colicWeeks >= 0) {
document.getElementById('totalWeeks').style.display = 'block';
var barData = {
labels: ["50% Probability", "80% Probability", "95% Probability", "99% Probability"],
datasets: [
{
label: "Birth No Condition",
fillColor: "#137fc1",
strokeColor: "#137fc1",
data: [c50F, c80F, c95F, c99F]
},
{
label: "Current Age",
fillColor: "#ff0000",
strokeColor: "#ff0000",
data: [
finalAge50,
finalAge80,
finalAge95,
finalAge99
]
}
]
}
document.getElementById('myChart').style.display = 'block';
var myChart = document.getElementById("myChart").getContext("2d");
if (myBarChart !== undefined)
myBarChart.destroy();
myBarChart = new Chart(myChart).StackedBar(barData, {
scaleShowLabels: true,
responsive: true
});
} else {
document.getElementById('myChart').style.display = 'none';
document.getElementById('totalWeeks').style.display = 'none';
}
divobj.innerHTML = "Your child has currently had colic for " + colicWeeks + " weeks. <br /><br />Their is a " + p50 + "% chance that your childs colic will end in " + c50F + " weeks at " + finalAge50 + " weeks of age. <br /><br />Their is a " + p80 + "% chance that your childs colic will end in " + c80F + " weeks at " + finalAge80 + " weeks of age. <br /><br />Their is a " + p95 + "% chance that your childs colic will end in " + c95F + " weeks at " + finalAge95 + " weeks of age. <br /><br />Their is a " + p99 + "% chance that your childs colic will end in " + c99F + " weeks at " + finalAge99 + " weeks of age.";
}
var myBarChart;
function hideTotal() {
var divobj = document.getElementById('totalWeeks');
divobj.style.display = 'none';
document.getElementById('myChart').style.display = 'none';
}
then add a canvas element, probably after the results block
<div id="totalWeeks"></div>
<canvas id="myChart"></canvas>