How to draw google line chart with multiple strings data - javascript

I want to display the results of students using a single chart.
There are 4 exam phases in a year and 5 activities in each phase and each activity has grades ranging from A to G.
I'm using google line chart for this purpose.
Code for Generating the graph
[<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawLineChart);
function drawLineChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Phase');
data.addColumn('string', 'Activity 1');
data.addColumn('string', 'Activity 2');
data.addColumn('string', 'Activity 3');
data.addColumn('string', 'Activity 4');
data.addColumn('string', 'Activity 5');
data.addRows([
['1', 'A','B','C','D','E'],
['2', 'E','D','C','B','A'],
['3', 'A','B','C','D','E'],
['4', 'E','D','C','B','A'],
]);
var options = {
title: 'Student Result',
width: 600,
height: 550,
legend: { position: 'bottom' },
vAxis: { ticks: ['A','B','C','D','E','F','G']}
};
var chart = new google.charts.Line(document.getElementById('line_top_x'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
</script>
</head>
<body>
<div id="line_top_x"></div>
</body>
</html>
Link to the Output of this code
The axis is null. It is not generating the chart as per data.

if you check the data format for a line chart,
only the first column in the data table may be of type 'string',
the rest should be 'number'
in this case, you could convert each grade to a number.
then use object notation to show the grade instead of the number.
using object notation allows you to provide the value (v:) and the formatted value (f:)
{v: 0, f: 'A'}
the formatted value is displayed by default.
next, if you want to customize the vertical axis, by using ticks,
you won't be able to use a material chart --> google.charts.Line
you will need to use a classic chart instead --> google.visualization.LineChart
there are several options that are not supported by material charts, including ticks
see Tracking Issue for Material Chart Feature Parity for more info.
see following working snippet for an example...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
var scale = {
'A': 0,
'B': 1,
'C': 2,
'D': 3,
'E': 4,
'F': 5,
'G': 6
};
var grades = [
['1','A','B','C','D','E'],
['2','E','D','C','B','A'],
['3','A','B','C','D','E'],
['4','E','D','C','B','A']
];
var data = new google.visualization.DataTable();
data.addColumn('string', 'Phase');
data.addColumn('number', 'Activity 1');
data.addColumn('number', 'Activity 2');
data.addColumn('number', 'Activity 3');
data.addColumn('number', 'Activity 4');
data.addColumn('number', 'Activity 5');
grades.forEach(function (activities) {
var row = [];
activities.forEach(function (grade, indexGrade) {
if (indexGrade === 0) {
row.push(grade);
} else {
row.push({
v: scale[grade],
f: grade
});
}
});
data.addRow(row);
});
var options = {
title: 'Student Result',
width: 600,
height: 550,
legend: {
position: 'bottom'
},
vAxis: {
ticks: [
{v: 0, f: 'A'},
{v: 1, f: 'B'},
{v: 2, f: 'C'},
{v: 3, f: 'D'},
{v: 4, f: 'E'},
{v: 5, f: 'F'},
{v: 6, f: 'G'}
]
}
};
var chart = new google.visualization.LineChart(document.getElementById('line_top_x'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="line_top_x"></div>

Related

Google chart API: Set values of node labels in Sankey diagram

I am trying to create a simple Sankey diagram showing flows between two sets of nodes, and would like the two sets to have the same names. However, this isn't allowed (it brings up a "Cycle found in rows" error), so I add "2" to the names of the nodes in the second set, like so:
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'From');
data.addColumn('string', 'To');
data.addColumn('number');
data.addRows([
['foo', 'foo2', 6],
['bar', 'bar2', 4],
['foo', 'bar2', 6],
['bar', 'foo2', 4]
]);
var chart = new google.visualization.Sankey(document.getElementById('sankey_basic'));
chart.draw(data);
}
However, I don't want the node labels to say "foo2" and "bar2" -- I just want them to say "foo" and "bar". In some cases in Google Visualization API you can solve this problem with {v: 'foo2', f: 'foo'} and {v: 'bar2', f: 'bar'}, but that doesn't work here. Is there any way I can do this?
try using a space at the end...
['foo', 'foo ', 6],
['bar', 'bar ', 4],
['foo', 'bar ', 6],
['bar', 'foo ', 4]
see following working snippet...
google.charts.load('current', {
packages: ['sankey']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'From');
data.addColumn('string', 'To');
data.addColumn('number');
data.addRows([
['foo', 'foo ', 6],
['bar', 'bar ', 4],
['foo', 'bar ', 6],
['bar', 'foo ', 4]
]);
var chart = new google.visualization.Sankey(document.getElementById('sankey_basic'));
chart.draw(data);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="sankey_basic"></div>

Double Y axis ticks for Google Charts

I am trying to set ticks for a double y-axis line graph but either the graph wont load, it it loads exactly the same. Any help will be greatly appreciated
Goal is to set Price ticks: [0.002, 0.004. 0.006. 0.008], and Volume increment by lets say 1000
Also having issues with prices for instance being: 0.00242, 0.00521 all showing up as 0.1
<?php
$sql = "SELECT Timestamp, LastPrice, Volume FROM vol";
$result = $dbconnect->query($sql);
?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
google.charts.load('current', {'packages':['line', 'corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var button = document.getElementById('change-chart');
var chartDiv = document.getElementById('chart_div');
var data = google.visualization.arrayToDataTable([
['Timestamp','LastPrice','Volume'],
<?php
while($row = mysqli_fetch_assoc($result)){
echo "[ '".$row["Timestamp"]."', ".$row["LastPrice"].", ".$row["Volume"].", ],";
}
echo $row["LastPrice"];
?>
]);
var materialOptions = {
chart: {
},
width: 600,
height: 300,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: {axis: 'LastPrice' },
1: {axis: 'BaseVolume'}
},
vAxis: {1: {ticks:[0, 0.002, 0.004, 0.006]} },
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
LastPrice: {label: 'Price'},
BaseVolume: {label: 'Volume'}
}
}
};
function drawMaterialChart() {
var materialChart = new google.charts.Line(chartDiv);
materialChart.draw(data, materialOptions);
button.innerText = 'Classic';
button.onclick = drawClassicChart;
}
drawMaterialChart();
}
</script>
there are several configuration options that aren't supported by Material charts, including...
{hAxis,vAxis,hAxes.*,vAxes.*}.ticks
see --> Tracking Issue for Material Chart Feature Parity
instead, recommend using a Classic chart with the following option...
theme: 'material'
for dual y-axis charts, use the series option to specify the target axis
series: {
1: {
targetAxisIndex: 1,
}
},
use option vAxes, with an e, to specify ticks for each y-axis
vAxes: {
0: {
ticks:[0, 1000, 2000, 3000],
title: 'Last Price'
},
1: {
ticks:[0, 0.002, 0.004, 0.006],
title: 'Base Volume'
}
}
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable({
cols: [
{label: 'x', type: 'string'},
{label: 'y0', type: 'number'},
{label: 'y1', type: 'number'}
],
rows: [
{c:[{v: 'row 0'}, {v: 1800}, {v: 0.00242}]},
{c:[{v: 'row 1'}, {v: 2200}, {v: 0.00521}]},
{c:[{v: 'row 2'}, {v: 2800}, {v: 0.00343}]},
{c:[{v: 'row 3'}, {v: 2800}, {v: 0.00441}]},
{c:[{v: 'row 4'}, {v: 2300}, {v: 0.00532}]}
]
});
var container = document.getElementById('chart');
var chart = new google.visualization.LineChart(container);
chart.draw(data, {
width: 600,
height: 300,
series: {
1: {
targetAxisIndex: 1,
}
},
theme: 'material',
vAxes: {
0: {
ticks:[0, 1000, 2000, 3000],
title: 'Last Price'
},
1: {
ticks:[0, 0.002, 0.004, 0.006],
title: 'Base Volume'
}
}
});
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>

Google Charts Legend Position Not Working

This is driving me nuts. I can't get the legend to move at all. This produces a chart with the legend in it's default location on the right.
I clearly have legend position declared as "bottom" but it's not working. Yet this is exactly what the docs say.
google.charts.load('current',{'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff(){
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Count');
data.addColumn('number', 'Variance');
data.addRows([
['Smith', 35, {v: -.1126, f: '-11.26%'} ],
['Chalk', 53, {v: -.0126, f: '-1.26%'} ],
['Hank', 84, {v: -.0252, f: '-2.52%'} ],
['Jordan', 46, {v: .0688, f: '6.88%'} ],
['Bernie', 1, {v: 0, f: '-'} ],
['Ralph', 105, {v: -.0548, f: '-5.48%'} ]
]);
var options = {
series: {
0: {axis: 'Quotes'},
1: {axis: 'Percent'}
},
axes: {
y: {
Quotes: {label: 'Subdmission Count'},
Percent: {label: '% Percent'}
}
},
legend: {
position : 'bottom'
}
};
var table = new google.charts.Bar(document.getElementById('table1'));
table.draw(data, options);
}
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id='table1'></div>
</body>
</html>
legend.position: ['top', 'bottom'] -- are just a couple of the many options that don't work on material charts
see Tracking Issue for Material Chart Feature Parity #2143 for an extensive list
however, these options will work on a core chart...
core --> google.visualization.ColumnChart -- using --> packages: ['corechart']
material --> google.charts.Bar -- using --> packages: ['bar']
there is also an option to get a core chart close to the look & feel of material
theme: 'material'
see following working snippet using core chart instead...
google.charts.load('current',{'packages':['corechart']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff(){
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Count');
data.addColumn('number', 'Variance');
data.addRows([
['Smith', 35, {v: -.1126, f: '-11.26%'} ],
['Chalk', 53, {v: -.0126, f: '-1.26%'} ],
['Hank', 84, {v: -.0252, f: '-2.52%'} ],
['Jordan', 46, {v: .0688, f: '6.88%'} ],
['Bernie', 1, {v: 0, f: '-'} ],
['Ralph', 105, {v: -.0548, f: '-5.48%'} ]
]);
var options = {
chartArea: {
height: '56%'
},
series: {
1: {
targetAxisIndex: 1
}
},
hAxis: {
title: 'Name'
},
vAxes: {
0: {
title: 'Submission Count'
},
1: {
title: '% Percent'
}
},
theme: 'material',
legend: {
position : 'bottom'
}
};
var table = new google.visualization.ColumnChart(document.getElementById('table1'));
table.draw(data, options);
}
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id='table1'></div>
</body>
</html>
{position: 'left'} works fine in your example, so the only option left is that 'bottom' this is not supported.
Similar discussion on guthub mentions that it is not supported for another chart type and not planned to be implemented: https://github.com/google/google-visualization-issues/issues/1964

Google charts annotation not showing

I am using the google charts api to display data from php. I am displaying this information in a material style bar chart (vertical).
I am trying to add annotations to show the values inside the bars however it isn't working.
JavaScript:
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawLastPackets);
function drawLastPackets() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Days');
data.addColumn('number', 'Packets Packed');
data.addColumn({type: 'string', role: 'annotation'});
data.addRows(<?php echo json_encode($chartLastPackets); ?>);
var toAdd = ["Day", "Packets Packed", {"role": "annotation"}];
var options = {
legend: {
position: 'none',
},
series: {
0: {color: '#d7a8a8'}
},
vAxis: {
title: 'Packets'
}
};
var chart = new google.charts.Bar(document.getElementById('lastPackets'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
The contents of the php array $chartLastPackets is:
[["Mon", 1, "1"], ["Tue", 3, "3"], ["Wed", 5, "5"], ["Thu", 2, "2"], ["Fri", 0, "0"]]
However all I can see is the chart itself without the annotation.
annotations.* are listed among the several options that don't work on Material charts
you can use the following option, to get the chart close to the look & feel of Material
theme: 'material'
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Days');
data.addColumn('number', 'Packets Packed');
data.addColumn({type: 'string', role: 'annotation'});
data.addRows([["Mon", 1, "1"], ["Tue", 3, "3"], ["Wed", 5, "5"], ["Thu", 2, "2"], ["Fri", 0, "0"]]);
var options = {
legend: {
position: 'none',
},
series: {
0: {color: '#d7a8a8'}
},
theme: 'material',
vAxis: {
title: 'Packets'
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('lastPackets'));
chart.draw(data, options);
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="lastPackets"></div>

google charts api - column chart - percentage above vertical bar along with normal values on left side of vaxis

I am using google charts to generate a column chart as shown in this image:
http://postimg.org/image/mt7tzwwob/
Here, data will be like [['a', 1], ['b', 2], ['c', 3]]
Here, I am getting values 1,2,3 on left left side of vaxis which is ok for me.
What I want extra is: The percentages at the top of the vertical bar.
x+2x+3x = 100, means, x=16, 2x=33, 3x=50. So, 16% should be at top of vertical bar with value 1.
How can I get these percentages ?
The ColumnChart's don't support adding labels like a percentage above the columns, but there is a work-around that involves using a ComboChart and a hidden line to add them in. Here's some example code that adds in labels (you can replace the labels with percents in you want):
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Value');
data.addColumn({type: 'string', role: 'annotation'});
data.addRows([
['Foo', 53, 'Foo text'],
['Bar', 71, 'Bar text'],
['Baz', 36, 'Baz text'],
['Cad', 42, 'Cad text'],
['Qud', 87, 'Qud text'],
['Pif', 64, 'Pif text']
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, 1, 2]);
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(view, {
height: 400,
width: 600,
series: {
0: {
type: 'bars'
},
1: {
type: 'line',
color: 'grey',
lineWidth: 0,
pointSize: 0,
visibleInLegend: false
}
},
vAxis: {
maxValue: 100
}
});
}
see it working here: http://jsfiddle.net/asgallant/QjQNX/
This only works well for charts that have a single series of data (as the labels will be misaligned if there is more than one series).

Categories

Resources