Draw two lines in column chart google charts - html

I am trying to draw two lines using google combo charts, I am referring this link https://developers.google.com/chart/interactive/docs/gallery/combochart
but I am able to draw only one line!!!
function drawchart1(dataValues) {
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
var data = new google.visualization.DataTable();
data.addColumn('string', 'KPI_MONTH');
data.addColumn('number', 'DIE');
data.addColumn('number', 'DIE_TS');
data.addColumn('number', 'DIE_LL');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].KPI_MONTH, dataValues[i].DIE, dataValues[i].DIE_TS, dataValues[i].DIE_LL]);
}
// Instantiate and draw our chart, passing in some options
var chart = new google.visualization.ComboChart(document.getElementById('ColumnChart'));
//var chart1 = new google.visualization.PieChart(document.getElementById('piechart1'));
chart.draw(data,
{
title: "Column Chart of Google Chart in Asp.net",
position: "top",
fontsize: "14px",
seriesType: 'bars',
series: { 2: { type: 'line' } },
series: { 1: { type: 'line' } },
chartArea: { width: '50%' },
});
Only for the series 1 graph is getting generated like below.Only one line is geeting generated in this graph

The chart options should only have one key for series, which can have multiple series definitions.
series: {
1: { type: 'line' },
2: { type: 'line' }
},
Example...
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawchart1
});
function drawchart1(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'KPI_MONTH');
data.addColumn('number', 'DIE');
data.addColumn('number', 'DIE_TS');
data.addColumn('number', 'DIE_LL');
data.addRow(['Jan-15', 80, 90, 80]);
data.addRow(['Feb-15', null, 90, 80]);
data.addRow(['Mar-15', 100, 90, 80]);
data.addRow(['Apr-15', 100, 90, 80]);
data.addRow(['May-15', 20, 90, 80]);
data.addRow(['Jun-15', 30, 90, 80]);
data.addRow(['Jul-15', 10, 90, 80]);
data.addRow(['Aug-15', 50, 90, 80]);
data.addRow(['Sep-15', 30, 90, 80]);
data.addRow(['Oct-15', 10, 90, 80]);
data.addRow(['Nov-15', 20, 90, 80]);
data.addRow(['Dec-15', 100, 90, 80]);
var chart = new google.visualization.ComboChart(document.getElementById('ColumnChart'));
chart.draw(data,
{
title: "Column Chart of Google Chart in Asp.net",
position: "top",
fontsize: "14px",
seriesType: 'bars',
series: {
1: { type: 'line' },
2: { type: 'line' }
},
chartArea: { width: '50%' },
});
}
<script src="https://www.google.com/jsapi"></script>
<div id="ColumnChart"></div>

Related

Highcharts series data from JSON object

I am new to JSON and mvc so here is my issue. I am currently working on graphs using highcharts. I have a controller which returns a JSON object.
public JsonResult _GetChart_TrendPublicationTypeDetailed_Data(int
yearToDisplay)
{
//Types of publications to be considered
string[] publication_types = new string[] { "article", "book", "book_section", "conference_proceedings" };
//Get the list of outputs with usp authors
var uspPubs = _uspAuthoredPublications();
//List of years for which to display the data
List<int> yearRange = _getListOfYears(yearToDisplay, yearRangeFactor_10);
//Get the data
var data = from eprint_summary in localDB.Summary
where
eprint_summary.Year > (yearToDisplay - yearRangeFactor_10)
&& eprint_summary.Year <= yearToDisplay
&& publication_types.Contains(eprint_summary.TypeCode)
&& uspPubs.Contains(eprint_summary.EprintId)
//&& eprint_summary.refereed == "TRUE" //TODO: Confirm whether we need this filter in our counts
group eprint_summary by new { eprint_summary.Year, eprint_summary.TypeDesc } into typeTrend
orderby typeTrend.Key.Year, typeTrend.Key.TypeDesc
select new
{
Year = typeTrend.Key.Year,
Type = typeTrend.Key.TypeDesc,
Count = typeTrend.Count()
};
//Extract the series data
List<object> countData = new List<object>();
foreach (var item in data.ToList().Select(y => y.Type).Distinct().OrderBy(y => y))
{
List<int> yearlyData = new List<int>();
foreach (var year in yearRange)
{
var rec = data
.Where(y => y.Type == item)
.Where(y => y.Year == year)
.Select(y => y.Count).ToArray();
yearlyData.Add(
rec == null || rec.Length == 0 ? 0 : rec[0]
);
}
countData.Add(
new
{
name = item, //Name of the series
data = yearlyData.ToArray() //Array of data
}
);
}
//Form the json object using the series data and labels
return Json(
new
{
labels = yearRange.ToArray(),
series = countData
},
JsonRequestBehavior.AllowGet
);
}
The above is my JSON in controller.
I have my view as below where I am getting the JSON object but I do not know how to append to my graph as series. How would I convert the JSON object to something that the series accepts.
var seriesData = ' ';
var test = ' ';
function ajaxCall() {
$.ajax({
type: "post",
datatype: "Json",
async: true,
url: '#Url.Action("_GetChart_TrendPublicationTypeDetailed_Data", "ResearchCharts")',
data: { yearToDisplay: '#(DateTime.Now.AddYears(-1).Year.ToString())' },
success: function (data) {
seriesData = data;
test = seriesData.series;
//bindChart(test);
//alert(JSON.stringify(seriesData));
alert(JSON.stringify(test));
},
error: function () {
alert("An error occurred.");
}
});
}
//functions call
ajaxCall();
bindChart(test);
function bindChart(test) {
var test2 = [{ "name": "Book", "data": [14, 17, 9, 10, 6, 19, 6, 8, 0, 4] }, { "name": "Book Chapter", "data": [65, 74, 44, 66, 9, 23, 36, 51, 53, 36] }, { "name": "Conference Proceedings", "data": [15, 17, 27, 30, 28, 54, 35, 43, 50, 35] }, { "name": "Journal Article", "data": [178, 162, 133, 139, 133, 191, 160, 194, 149, 169] }];
$('#chartTrendsPublicationTypeDetailed').highcharts({
chart: {
type: 'line'
},
title: {
text: 'My data'
},
xAxis: {
categories: ['2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016']
},
series: test2//[{ "name": "Book", "data": [14, 17, 9, 10, 6, 19, 6, 8, 0, 4] }, { "name": "Book Chapter", "data": [65, 74, 44, 66, 9, 23, 36, 51, 53, 36] }, { "name": "Conference Proceedings", "data": [15, 17, 27, 30, 28, 54, 35, 43, 50, 35] }, { "name": "Journal Article", "data": [178, 162, 133, 139, 133, 191, 160, 194, 149, 169] }]
});
Please help, just need to somehow pass the data to highcharts.
in the picture, I have added the series manually and it works, but I need to pass in a variable which the series property accepts.
Old Highcharts rendering code:
$('#chartTrendsPublicationRankDetailed').highcharts({
chart: {
type: 'line'
},
title: {
text: 'My data'
},
xAxis: {
categories: labels
},
series: seriesData
});
New Highcharts rendering code. This accepts my JSON objects successfully and renders the graphs.
function bindChartItemType(seriesData, labels) {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chartTrendsPublicationTypeDetailed',
type: 'line',
height: 500,
width: 500
},
credits: {
enabled: false
},
title: {
text: 'Trend of Publications by Item Type'
},
xAxis: {
categories: labels,
title: {
text: '<b>Year</b>'
}
},
yAxis: {
min:0,
title: {
text: '<b># of publications</b>'
}
},
series: seriesData
});
}
Feel free to add anything you like in the comments.
Regards
Shafraz Buksh

Highcharts stacked bar data from CSV

I'm trying to implement a stacked bar chart with data coming from a CSV.
I need to update series: with the data from the CSV file which contains, for example "John,10,5,3,4,1".
Help please!
$(function () {
$('#container').highcharts({
chart: {
type: 'bar'
},
title: {
text: 'Stacked bar chart'
},
xAxis: {
categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
},
yAxis: {
min: 0,
title: {
text: 'Total fruit consumption'
}
},
legend: {
reversed: true
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
});
});
UPDT
I finally got it working, but still there's a problem. The bars are inverted and I need them to be exactly in the same order as in the CSV file.
Here's my parser:
$.get('chart.csv', function(data) {
var lines=data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
});
var chart = new Highcharts.Chart(options);
The contents of the CSV file:
Disconnection,30,30
Site Care,12,12
Documentation,35,35
Lining,22,22
Connection,70,52
I need the stacked bars in the same order as in the legend:
http://i.stack.imgur.com/6EkHg.png
You could try to custom setting the series indices before you render the chart to fix the inversion of the bars.
Something like this might do the trick:
for (var i = 0; i < options.series.length; i++) {
options.series[i].index = options.series.length - 1 - i;
options.series[i].legendIndex = i;
}

google is not defined in mvc4

I am trying to render google geochart inside partial view in mvc4 but it's showing reference error:
"google is not defined"
but in simple view it's rendering fine.below is step to render my geochat.i don't know what i am doing wrong or should fellow other step to render google geochat.
my partial view(_mymap.cshtml)
<script type='text/javascript' src='http://www.google.com/jsapi'></script>
<div id='visualization'></div>
<script type='text/javascript'>
function initialize() {
google.load('visualization', '1', { 'packages': ['geochart'] });
google.setOnLoadCallback(drawVisualization);
}
function drawVisualization() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'Value');
data.addColumn({ type: 'string', role: 'tooltip' }); var ivalue = new Array();
data.addRows([[{ v: '002', f: 'Africa' }, 0, 'Click to Choose']]);
ivalue['002'] = 'http://en.wikipedia.org/wiki/Africa';
data.addRows([[{ v: '150', f: 'Europe' }, 1, 'Click to Choose']]);
ivalue['150'] = 'http://en.wikipedia.org/wiki/Europe';
data.addRows([[{ v: '019', f: 'Americas' }, 2, 'Click to Choose']]);
ivalue['019'] = 'http://en.wikipedia.org/wiki/Americas';
data.addRows([[{ v: '142', f: 'Asia' }, 3, 'Click to Choose']]);
ivalue['142'] = 'http://en.wikipedia.org/wiki/Asia';
data.addRows([[{ v: '009', f: 'Australia' }, 4, 'Click to Choose']]);
ivalue['009'] = 'http://en.wikipedia.org/wiki/Oceania';
var options = {
backgroundColor: { fill: '#FFFFFF', stroke: '#FFFFFF', strokeWidth: 0 },
colorAxis: { minValue: 0, maxValue: 4, colors: ['#A8A8A8', '#939473', '#B1B38B', '#90AD89', '#87AAAD', ] },
legend: 'none',
backgroundColor: { fill: '#FFFFFF', stroke: '#FFFFFF', strokeWidth: 0 },
datalessRegionColor: '#f5f5f5',
displayMode: 'regions',
enableRegionInteractivity: 'true',
resolution: 'continents',
sizeAxis: { minValue: 1, maxValue: 1, minSize: 10, maxSize: 10 },
region: 'world',
keepAspectRatio: true,
width: 600,
height: 400,
tooltip: { textStyle: { color: '#444444' }, trigger: 'focus' }
};
var chart = new google.visualization.GeoChart(document.getElementById('visualization'));
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
//append_to_list(data.getValue(selection[0].row, 0));
});
chart.draw(data, options);
}
$(document).ready(function () {initialize();});
</script>
drawVisualization function is missing closing brace inside script tag. You have closed it after the end script tag in your code.
$(document).ready(function () {initialize();});
</script>
} //this brace need to be inside script tag
The loader uses document.write to inject JS and CSS, this can't be done after the document has finished loading(what is the case here, because you call initialize on domready)
define the callback in the call of google.load and not via setOnLoadCallback
function initialize() {
google.load('visualization',
'1',
{ 'packages': ['geochart'] , callback: drawVisualization});
}

How do I properly format a JSON object in an external file?

I have used the code available from http://codeblitz.wordpress.com/2009/06/22/jquery-charts/
It uses jqPlot. So I have the following sample code Default.html that works:
<script type="text/javascript">
var jsonObj = { "pageHits": [30, 60, 22, 5, 60, 88, 102], "rssHits": [33, 45, 121, 23, 55, 35, 77], "xAxis": ['Jan 2009', 'Feb 2009', 'Mar 2009', 'Apr 2009', 'May 2009', 'June 2009', 'Jul 2009'] };
$(function () {
$.jqplot('chartDiv', [jsonObj.pageHits, jsonObj.rssHits], CreateBarChartOptions());
});
function CreateBarChartOptions()
{
var optionsObj = {
title: 'Blog Statistics',
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: jsonObj.xAxis
}
},
series: [{label:'Page Hits'}, {label: 'RSS Hits'}],
legend: {
show: true,
location: 'nw'
},
seriesDefaults:{
shadow: true,
renderer:$.jqplot.BarRenderer,
rendererOptions:{
barPadding: 8,
barMargin: 10
}
},
highlighter: {
showTooltip: true,
tooltipFade: true
}
};
return optionsObj;
}
</script>
I have copied the code and put it into Default.aspx. The only thing I want to change is to be able to get the data from an external file, so now my code is:
<script type="text/javascript">
var jsonObj;
$.getJSON('example.json', function (response)
{
jsonObj = response;
alert(jsonObj.property);
});
$(function () {
$.jqplot('chartDiv', [jsonObj.pageHits, jsonObj.rssHits], CreateBarChartOptions());
});
function CreateBarChartOptions()
{
var optionsObj = {
title: 'Blog Statistics',
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: jsonObj.xAxis
}
},
series: [{ label: 'Page Hits' }, { label: 'RSS Hits'}],
legend: {
show: true,
location: 'nw'
},
seriesDefaults: {
shadow: true,
renderer: $.jqplot.BarRenderer,
rendererOptions: {
barPadding: 8,
barMargin: 10
}
},
highlighter: {
showTooltip: true,
tooltipFade: true
}
};
return optionsObj;
}
</script>
But jsonObj is always undefined, I'm presuming my file is not formatted properly. I have tried example.json to contain this:
{"pageHits": [30, 60, 22, 5, 60, 88, 102], "rssHits": [33, 45, 121, 23, 55, 35, 77], "xAxis": ['Jan 2009', 'Feb 2009', 'Mar 2009', 'Apr 2009', 'May 2009', 'June 2009', 'Jul 2009']}
and this:
{"pageHits": [30, 60, 22, 5, 60, 88, 102], "rssHits": [33, 45, 121, 23, 55, 35, 77], "xAxis": ["Jan 2009", "Feb 2009", "Mar 2009", "Apr 2009", "May 2009", "June 2009", "Jul 2009"]}
But to no avail. What am I doing wrong?
Thanks for any assistance,
Julian
You'd probably need to do something like:
$.getJSON('example.json', function (response)
{
var jsonObj = response;
$.jqplot('chartDiv', [jsonObj.pageHits, jsonObj.rssHits], CreateBarChartOptions());
});
The way you have it now your annon function to trigger jqplot will run 'inline', while the ajax loading will still be going on.

Drawing charts on html5 canvas using jqplot

I am using jqplot charts for drawing different charts on html5 canvas. All charts are working well in all browsers but vertical bar(stacked and clustered) and line charts are getting overlapped in safari. Any reason why is this happening?
The following code lines i have used to draw clustered bar chart:
function DrawChart(chartId, chartType, categories, seriesWithData, grouping)
{
/*for(var i=0;i<seriesWithData.length;i++)
{
eachSeriesArr = seriesWithData[i].split(";");
seriesLabels[i] = eachSeriesArr.splice(0,1);
eachSeriesArr.splice(eachSeriesArr.length-1, 1);
for(var j=0; j<eachSeriesArr.length;j++)
{
eachSeriesArr[j] = Math.round(eachSeriesArr[j]).toString();
}
globalSeriesArr.push(eachSeriesArr);
} */
// Testing with hard coded value
var s1 = [2, 6, 7, 10];
var s2 = [7, 5, 3, 4];
var s3 = [14, 9, 3, 8];
plotChart = $.jqplot(chartId, [s1,s2,s3], {
seriesDefaults:{
showLabel: true,
renderer:$.jqplot.BarRenderer,
rendererOptions: {
fillToZero: true,
//showDataLabels: true,
barDirection: 'vertical',
},
pointLabels: {show: true}
},
axesDefaults: {
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
autoscale: true,
},
axes: {
// Use a category axis on the x axis and use our custom ticks.
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: categories,
},
yaxis: { pad: 1.0 }
},
legend: {show: true, placement: 'outside', location: 'e' },
});
}
//This is the canvas div in html file
<div id="rId2" style="width:640px;height:426px;"></div>
<script type="text/javascript">
$(document).ready(function(){
alert('document loaded completely');
DrawChart('rId2', 'barChart;col', new Array(
"Category 1",
"Category 2",
"Category 3",
"Category 4"
), new Array(
"Series 1;4.3;2.5;3.5;4.5;",
"Series 2;2.4;4.4000000000000004;1.8;2.8;",
"Series 3;2;2;3;5;"
), 'clustered')
});
</script>
`
I am calling this function (defined in a javascript file) on document ready function from html file
Is anything missing?