Combining style, interval and certainty in Google Charts - google-visualization

Have a look at https://jsfiddle.net/DavidHyde/fkuonb5s/. This is based on an example from the Google Charts documentation along with the code that I'm running. I didn't write the code and am not a Charts expert by any means, so don't understand all the code yet.
Anyway, I'm having trouble combining the style, interval and certainty roles. It seems that I can apply any one, but when I have two or more, only the first is applied.
Specifying "certainty" gives this:
Applying "style" gives this:
and this is just "interval"
What I really want to do is apply the certainty role for the hatching, and the interval role for the horizontal bar.
Can anyone help? Thanks
StackOverflow says that any jsfiddle.net must be accompanied by code, so here it is...
google.charts.load('current', { packages: ['corechart', 'bar'] });
google.charts.setOnLoadCallback(drawRightY);
function drawRightY() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month'); // Implicit domain label col.
data.addColumn('number', 'Sales'); // Implicit series 1 data col.
data.addColumn({ type: 'boolean', role: 'certainty' }); // certainty col.
data.addColumn({ type: 'string', role: 'style' }); // style col.
data.addColumn({ type: 'number', role: 'interval' }); // interval role col.
data.addColumn({ type: 'number', role: 'interval' }); // interval role col.
data.addColumn({ type: 'string', role: 'annotation' }); // annotation role col.
data.addColumn({ type: 'string', role: 'annotationText' }); // annotationText col.
data.addRows([
['April', 1000, true, 'stroke-color: #703593; stroke-width: 4', 900, 1100, 'A', 'Stolen data'],
['May', 1170, true, 'stroke-color: #703593; stroke-width: 4; color: #C5A5CF', 1000, 1200, 'B', 'Coffee spill'],
['June', 660, true, 'fill-color: red; fill-opacity:.3', 550, 800, 'C', 'Wumpus attack'],
['July', 1030, false, null, 100, 300, null, null]
]);
var barOptions = new google.visualization.ComboChart(document.getElementById('chart_div'));
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 2]);
var barSetting = {
seriesType: "bars",
areaOpacity: 0.1,
orientation: 'horizontal',
series: { 2: { 'lineWidth': 5, 'barWidth': 1, 'color': '#000000', type: 'line' } },
legend: 'none',
vAxis: {
maxValue: 100,
minValue: 0,
format: "#'%'"
},
hAxis: {
textStyle: {
fontSize: 9
}
},
colors: ["#fbbd86", "#000000", "#000000", "#000000"],
height: 200,
width: 420
};
barSetting.intervals = { 'lineWidth': 5, 'barWidth': 1, style: 'box', 'color': '#000000' };
barOptions.draw(view, barSetting);
}

Here is the updated jsfiddle from #dlaliberte showing the chart working - https://jsfiddle.net/dlaliberte/cvu3t7se/6/.
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawRightY);
function drawRightY() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month'); // Implicit domain label col.
data.addColumn('number', 'Sales'); // Implicit series 1 data col.
data.addColumn({ type: 'boolean', role: 'certainty' }); // certainty col.
data.addColumn({ type: 'string', role: 'style' }); // style col.
data.addColumn({ type: 'number', role: 'interval' }); // interval role col.
data.addColumn({ type: 'number', role: 'interval' }); // interval role col.
data.addColumn({ type: 'string', role: 'annotation' }); // annotation role col.
data.addColumn({ type: 'string', role: 'annotationText' }); // annotationText col.
data.addRows([
[
'April'
, 1000
, true
, 'stroke-color: #703593; stroke-width: 4'
, 900
, 1100
, 'A'
, 'Stolen data'
],
[
'May'
, 1170
, true
, 'stroke-color: #703593; stroke-width: 4; color: #C5A5CF'
, 1000
, 1200
, 'B'
, 'Coffee spill'
],
[
'June'
, 660
, true
, 'fill-color: red; fill-opacity:.3'
, 550
, 800
, 'C'
, 'Wumpus attack'
],
[
'July'
, 1030
, false
, null
, 100
, 300
, null
, null
]
]);
var barOptions = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 2, 3, 4, 5, 6, 7]);
var barSetting = {
// seriesType: "bars",
//intervals: { 'lineWidth': 5, 'barWidth': 1, style: 'box', 'color': '#000000' },
areaOpacity: 0.1,
orientation: 'horizontal',
xseries: { 0: { 'lineWidth': 5, 'barWidth': 1, 'color': '#000000', type: 'line' } },
legend: 'none',
vAxis: {
maxValue: 100,
minValue: 0,
format: "#'%'"
},
hAxis: {
textStyle: {
fontSize: 9
}
},
colors: ["#fbbd86", "#000000", "#000000", "#000000"],
height: 200,
width: 420
};
barSetting.intervals = { 'lineWidth': 5, 'barWidth': 1, style: 'box', 'color': '#000000' };
barOptions.draw(view, barSetting);
}

Related

Adding line over stacked line chart with ChartJS

I'm trying to recreate this below chart with a stacked option on my background lines
But my attempts were unsuccessful with this image below as result
$(function() {
var areaChartCanvas = $('#areaChart').get(0).getContext('2d')
var areaChartData = {
labels: ['', '', ''],
datasets: [{
backgroundColor: 'transparent',
borderColor: 'black',
pointRadius: false,
data: [32, 12, 28],
type: 'line'
}, {
backgroundColor: 'red',
pointRadius: false,
data: [20, 20, 20]
}, {
backgroundColor: 'orange',
pointRadius: false,
data: [40, 40, 40]
}, {
backgroundColor: 'cyan',
pointRadius: false,
data: [60, 60, 60]
}]
}
var areaChartOptions = {
maintainAspectRatio: false,
responsive: true,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
display: true,
}
}],
yAxes: [{
gridLines: {
display: true,
},
stacked: true
}]
}
}
var areaChart = new Chart(areaChartCanvas, {
type: 'line',
data: areaChartData,
options: areaChartOptions
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script>
<canvas id="areaChart" style="height:250px"></canvas>
ideally, I want to be able to create 'AREAS' with different colors that will be stacked according to the interval I pass to it.
e.g:
cyan - 20
orange - 20
red - 20
but currently, I'm doing
cyan - 60
orange - 40
red - 20
If I understand you correctly, I thought about different approach and extends the chart with Plugin[1] (Inspired by https://stackoverflow.com/a/49303362/863110)
Chart.pluginService.register({
beforeDraw: function (chart, easing) {
if (chart.config.options.fillColor) {
var ctx = chart.chart.ctx;
var chartArea = chart.chartArea;
ctx.save();
let delta = 0;
const chartHeight = chartArea.bottom - chartArea.top;
const bottomBarHeight = chart.height - chartHeight - chartArea.top;
chart.config.options.fillColor.map(color => {
const colorHeight = chartHeight * (color[0] / 100);
const colorBottom = chartArea.bottom + colorHeight;
ctx.fillStyle = color[1];
const x = chartArea.left,
y = chart.height - bottomBarHeight - colorHeight - delta,
width = chartArea.right - chartArea.left,
height = colorHeight;
delta += height;
ctx.fillRect(x, y, width, height);
ctx.restore();
})
}
}
});
var chartData = {
labels: ['a', 'b', 'c', 'd'],
datasets: [{
label: 'value',
borderColor: 'blue',
data: [30, 50, 25, 10]
}]
};
var ctx = document.getElementById("myChart").getContext("2d");
var myBar = new Chart(ctx, {
type: 'line',
data: chartData,
options: {
scales: {
yAxes: [{ ticks: { max: 60 } }]
},
legend: { display: false },
fillColor: [
[20, 'red'],
[20, 'blue'],
[20, 'green'],
[20, 'pink'],
[20, 'yellow'],
]
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart" height="300" width="500"></canvas>
https://jsbin.com/lisuvuq/2/edit?js,output
[1] - With Plugin you can custom the chart's behaviour. When you use Plugin you get an API so you can "listen" to life cycle events of the chart (beforeDraw for example) and call your own code. The API calls your function and gives you data about the chart so you can use it in your code.In this example, we're using the API to (1) Run a code before the chart been drawing (2) Using the data to calculate the areas of the different colors. (3) Draw additional shapes (ctx.fillRect) based on the calculation.

Google line chart with multiple data

The below code to generate google line chart works fine with 2 values (Date and Mean) assigned. When I added more data (including Mode and Variance as shown below), it just shows the original datas (Date and Mean). The other data are not displayed. What am I doing wrong here? please. I am still learning google charts. Any help would be appreciated greatly. thanks.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
);
}
$query = "SELECT Date, Mean, Mode, Variance FROM datatb";
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Multiple Data</title>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
var data = google.visualization.arrayToDataTable([
['Date','Mean','Mode','Variance'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Date"]."', ".$row["Mean"].", ".$row["Mode"].", ".$row["Variance"]."],";
}
?>
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}]);
var options = {
title: 'Data',
hAxis : {textStyle : {fontSize: 8}},
'tooltip' : { trigger: 'none'},
enableInteractivity: false,
width: '100%',
height: '700',
chartArea:{
left:10,
top: 100,
width: '100%',
height: '450',
},
pointSize:4,
vAxis: { textPosition: 'none', gridlines: { count: 10 }, baselineColor: 'gray' },
annotations: { stemColor: 'white', textStyle: { fontSize: 11 } },
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curvechart'));
chart.draw(data, options);
chart.draw(view, options);
}
</script>
</head>
<body>
<div id="curvechart" style="width: 2500px; height: 600px"></div>
</body>
</html>
Whitehat's suggestion:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$con = new mysqli($servername, $username, $password, $dbname);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
else
{
);
}
$query = "SELECT Date, Mean, Mode, Variance FROM datatb";
$aresult = $con->query($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Multiple Data</title>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart(){
var data = new google.visualization.DataTable();
data.addColumn('number', 'Mode');
data.addColumn('number', 'Variance');
var data = google.visualization.arrayToDataTable([
['Date','Mean','Mode','Variance'],
<?php
while($row = mysqli_fetch_assoc($aresult)){
echo "['".$row["Date"]."', ".$row["Mean"].", ".$row["Mode"].", ".$row["Variance"]."],";
}
?>
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}, 2, {
calc: 'stringify',
sourceColumn: 2,
type: 'string',
role: 'annotation'
}, 3, {
calc: 'stringify',
sourceColumn: 3,
type: 'string',
role: 'annotation'
}, ]);
var options = {
title: 'Data',
hAxis : {textStyle : {fontSize: 8}},
'tooltip' : { trigger: 'none'},
enableInteractivity: false,
width: '100%',
height: '700',
chartArea:{
left:10,
top: 100,
width: '100%',
height: '450',
},
pointSize:4,
vAxis: { textPosition: 'none', gridlines: { count: 10 }, baselineColor: 'gray' },
annotations: { stemColor: 'white', textStyle: { fontSize: 11 } },
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curvechart'));
chart.draw(data, options);
chart.draw(view, options);
}
</script>
</head>
<body>
<div id="curvechart" style="width: 2500px; height: 600px"></div>
</body>
</html>
after correcting the echo statement, just need to add column to the view...
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}, 2, 3]);
or if you want all to have annotations...
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: 'stringify',
sourceColumn: 1,
type: 'string',
role: 'annotation'
}, 2, {
calc: 'stringify',
sourceColumn: 2,
type: 'string',
role: 'annotation'
}, 3, {
calc: 'stringify',
sourceColumn: 3,
type: 'string',
role: 'annotation'
}, ]);

Unable to display Axis title in google timeline chart

I have following code to display all the pool cars with engagement for a day. First thing I want is to display a fixed hAxis of 24 hours. And the axis title would be a plus. But as of now, it is displaying the time axis only till it has an engagement. And the title is not displaying at all. Thanks in advance for any help.
google.charts.load("current", {packages:["timeline"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var container = document.getElementById('chart_div');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'string', id: 'Vehicle' });
dataTable.addColumn({ type: 'string', id: 'Name' });
dataTable.addColumn({ type: 'date', id: 'Start' });
dataTable.addColumn({ type: 'date', id: 'End' });
dataTable.addRows([
[ 'SEDAN 10', 'Default Function', new Date(0,0,0,17,00,0), new Date(0,0,0,19,00,0) ],
[ 'SEDAN 11', 'IDLE', new Date(0,0,0,0,0,0), new Date(0,0,0,0,0,0) ],
[ 'SEDAN 12', 'IDLE', new Date(0,0,0,0,0,0), new Date(0,0,0,0,0,0) ],
[ 'SEDAN 13', 'IDLE', new Date(0,0,0,0,0,0), new Date(0,0,0,0,0,0) ],
[ 'SEDAN 14', 'IDLE', new Date(0,0,0,0,0,0), new Date(0,0,0,0,0,0) ] ]);
var options = {
hAxis: { title: 'Hours'},
viewWindow: {min: 0, max: 24},
ticks: [0, 6, 12, 18, 24]
timeline: {colorByRowLabel: true},
height: 800
};
chart.draw(dataTable, options);
}

Show Data Value in Column Chart Google Chart

I have created a chart using google-visualization but unable to get the data value for the second column
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,{
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
},
2]);
var options = {
title: 'Company Performance',
hAxis: { title: 'Users', titleTextStyle: { color: 'red', fontSize: 16} },
legend: { position: 'bottom', textStyle: { color: 'blue', fontSize: 16} }
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(view, options);
The data value comes for the sales but not to expense column
You need to add another annotation column to the view:
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation"
}, 2, {
calc: "stringify",
sourceColumn: 2,
type: "string",
role: "annotation"
}]);
dataView.setColumns([{ calc: function (data, row) { return data.getFormattedValue(row, 0); }, type: 'string' }, 1,2]);

google charts vAxis to the right

I'm using google visualization
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'time');
data2.addColumn('number', 'amount');
data2.addColumn({ type: 'string', role: 'tooltip' });
data2.addRows(rows_data);
var options2 = {
vAxis: { textPosition: 'none', title: '', textStyle: { fontName: 'arial'} },
hAxis: { slantedText: false, textStyle: { color: '#E6EFFA' }, gridlines: { color: '#E6EFFA', count: 20} },
backgroundColor: '#E6EFFA',
legend: 'none',
chartArea: { top: 0 },
colors: ['#435988'],
chartArea: { width: 800 }
};
chart2 = new google.visualization.LineChart(document.getElementById('chart_div_volume'));
I want the vAxis position to be on the right.
is it possible ?
Short Answer: Yes, but it's tricky.
Long Answer:
You need to set up a multi-axis chart. Basically, you create a dummy axis with no labels or anything to make it look like an axis. Then you configure a secondary axis. You create one set of dummy values (hidden) to put on the first axis, and plot your real data on the second.
Here is an example:
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Year', 'Dummy', 'Sales', 'Expenses'],
['2004', 0, 1000, 400],
['2005', null, 1170, 460],
['2006', null, 660, 1120],
['2007', null, 1030, 540]
]);
var options = {
title: 'Company Performance',
series: { 0: {targetAxisIndex: 0, visibleInLegend: false, pointSize: 0, lineWidth: 0},
1: {targetAxisIndex: 1},
2: {targetAxisIndex: 1}
},
vAxes: {
0: {textPosition: 'none'},
1: {},
}
};
var chart = new google.visualization.LineChart(document.getElementById('visualization'));
chart.draw(data, options);
}
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Productivity');
data.addColumn('number', 'Composite');
data.addColumn({ type: 'number', role: 'annotation' });
data.addColumn('number', 'Average(N=5)');
var compositeDataArry = [];
compositeDataArry.push(["Ravi", 11, 11, 5]);
compositeDataArry.push(["Wasif", 5, 5, 5]);
compositeDataArry.push(["Vipin", 2, 2, 5]);
compositeDataArry.push(["Ankur", 3, 3, 5]);
compositeDataArry.push(["Pankaj", 1, 1, 5]);
compositeDataArry.push(["Dheeraj", 4, 4, 5]);
data.addRows(compositeDataArry);
var options = {
title: 'My Chart',
titleTextStyle: { color: '#264158', fontSize: 24 },
seriesType: 'bars',
annotations: {
alwaysOutside: true,
textStyle: {
color: '#000000',
fontSize: 15
}
},
hAxis: {
slantedText: true,
slantedTextAngle: -45
},
series: {
0: { targetAxisIndex: 0, },
1: { targetAxisIndex: 1, type: 'line' }
},
vAxes: {
0: { textPosition: 'none' },
1: {}
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="chart_div" style="height: 500px; width: 100%"></div>
</body>
</html>