2015년 1월 3일 토요일

[visualization-api] "Pay it Forward" - A complete working Line Chart example

This Forum has been amazingly helpful to me in my quest to generate a series of moderately complex Line Charts on a web page from a collection of CVS data files.

After weeks of effort, I now have the kind of charting capability I have wanted for years to show critical home temperature values over time. One of these charts is shown below...


In an effort to "Pay it Forward" and help others, I have attached  a complete HTML/javaScript ("chartTemps.html") web page.  The kind of example I sought, but never found.

The attached file contents are also displayed below for quick reference.

The code is highly documented, in the hopes it will give you enough insight to explore further on your own, in order to meet your specific needs.

Enjoy, and thanks again to all those that helped me...

<html>
<head>
<style type="text/css">
<!--
.padding {padding-left: 40px;}
-->

</style>
<script src="https://www.google.com/jsapi"> </script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"> </script>
<script src="http://jquery-csv.googlecode.com/git/src/jquery.csv.js"></script>
<title>Environmental Temperatures</title>
<script>
// This is a general purpose Chart Handler, using the Google Charts API.
// It was designed to chart 5 temperature sensors, differentiating between current and old data values, which were written to a CVS file.
// The file has a header (for chart labeling use) and 5 sets of dual (left/right pair) columns.  Each column pair holds the new/old values for a sensor.
// Using SQL to hold and manage the temperature readings, at the beginning of each chart period (ie, x-axis value 0) all the values in the left
//   (new) column are moved to the right (old) column.  The new column chart lines are displayed as solid, while the old are shown as dashed.
// This clearly differentiates the current vs the historic values, while allowing a contiguous chart line.
// These vars are used for labeling the three charts produced by this code. A Day, Week, and Month chart.
var d = new Date();
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
var day = days[d.getDay()];
var month = months[d.getMonth()];
// Load the Visualization API from Google and set Listener
google
.load("visualization", "1.1", {packages:["corechart"]});
//google.setOnLoadCallback(drawChart);
// These calls (onLoad) call the three charts made with the 'drawChart' function, which has multiple parameters passed to it.
// The parameters cover the CSV file name; the vertical axis range and tick marking, the horizontal axis range and ticks; 
//  and finally the name of the division id used to place the chart in the body of the html page.
google
.setOnLoadCallback(function()
{
// parms--> ("fileName",cPeriod,vStrt,vStep,vEnd,vMaj,vMnr,  hStrt,hStep,hEnd,hMaj,hMnr,"divName")
   drawChart
("tempsDay.csv",day,-20,10,100,12,4, 0,1,24,24,3,"dayChart");
   drawChart
("tempsWeek.csv","Week (0=Sun; 6=Sat)",-20,10,100,12,4,0,1,7,7,5,"weekChart");
   drawChart
("tempsMonth.csv",month,-20,10,100,12,4,1,1,32,32,5,"monthChart");
});
function drawChart(fileName,cPeriod,vStrt,vStep,vEnd,vMaj,vMnr,hStrt,hStep,hEnd,hMaj,hMnr,divName) {
//    grab the CSV data and ready it for charting
   $
.get(fileName, function(csvString) {
 
// transform the CSV string into a 2-dimensional array
 
var arrayData = $.csv.toArrays(csvString, {onParseValue:$.csv.hooks.castToScalar});
 
//alert (arrayData[0]+ '\n' +  arrayData[1]);  //debug code to verify array contents
 
//alert(arrayData.join('\n'));  //this dumps the first and last portions of the array
// This new DataTable object holds all the data in Charting format
 
var data = google.visualization.arrayToDataTable(arrayData, false);
 
// The "data" view does not handle the case where a column may be totally blank (A sensor fails?).
// So creating a DataView isolates that problem.
    
var view = new google.visualization.DataView(data);
// The DataView allows us to force the column definitions to be numeric, so nulls don't cause a problem.
// Since we created a new view. we have to also import the CSV column labels.
 view
.setColumns([
 
{sourceColumn: 0, type: "number", label: data.getColumnLabel(0)},
 
// If imported labels are not used, then the "data.getColumnLabel()" parameter can be replaced with a label name (eg, "Outside Temp")
 
{sourceColumn: 1, type: "number", label: data.getColumnLabel(1)},
 
{sourceColumn: 2, type: "number"},
 
{sourceColumn: 3, type: "number", label: data.getColumnLabel(3)},
 
{sourceColumn: 4, type: "number"},
 
{sourceColumn: 5, type: "number", label: data.getColumnLabel(5)},
 
{sourceColumn: 6, type: "number"},
 
{sourceColumn: 7, type: "number", label: data.getColumnLabel(7)},
 
{sourceColumn: 8, type: "number"},
 
{sourceColumn: 9, type: "number", label: data.getColumnLabel(9)},
 
{sourceColumn: 10, type: "number"},
 
]);
 
var vStart = vStrt;
 
var vTicks = [];
 
while (vStart <= vEnd) {
 vTicks
.push(vStart);
 vStart
+=vStep;
 
}
 
var hStart = hStrt;
 
var hTicks = [];
 
while (hStart <= hEnd) {
 hTicks
.push(hStart);
 hStart
+=hStep;
 
}


 
var vAxisString= String.fromCharCode(176)+"F";

 
var options = {
 fontSize
: 8,
 legend
: 'true',
 legend
: {position: 'top'},
 chartArea
: {left: 40, top: 40, height: 270, width: 575},
 height
: 340, //This is the Total chart height size including the chartArea.height so make it = chartArea+70.
 width
: 625,  //Total chart width size including the chartArea.width so so make it = chartArea+50.
 title
: cPeriod, //day is computed from days[d.getDay()] in var definition above.
 titlePosition
: 'in',
 titleTextStyle
: {
 color
: '#70500B',  //Make Label brown in color
 fontSize
: 14
 
},
/*
 The Chart is formed from multiple temperature data streams (2 for each device sensed). Each data pair
 consists of a time sequence starting from 00:00 hours to the current time.  This "current" temp data, is
 placed in the left CSV column associated with each device (see CSV column definitions below). This data is
 represented on the chart by a solid colored line.


 The "historic" data (that data after the  current time and from the previous measuring period [ie, yesterday for the DAY
 chart]) is placed in the right CSV device data column and starts from the next time slot after the current time and
 runs until the end of the chart time period (ie, 24:00 hours for the DAY chart).  This data is charted as a dashed line
 (but can be changed in width and dash style using the "series" option parameters.

 CSV table columns are > Time,Dwn,Dwn.old,Mid,Mid.old,Out,Out.old,Frez,Frzr.old,Frig,Frig.old
*/

 series
: {
 
//  n:  {color: '#1DC70E',lineWidth:4,lineDashStyle: [3, 2] },
 
0: { color: '#E30805' }, //Dwn
 
1: { color: '#E30805',lineWidth:2,lineDashStyle: [3, 2],visibleInLegend: false }, //Dwn
 
2: { color: '#F78F07' }, //Mid
 
3: { color: '#F78F07',lineWidth:2,lineDashStyle: [3, 2],visibleInLegend: false }, //Mid
 
4: { color: '#1DC70E' }, //Out
 
5: { color: '#1DC70E',lineWidth:2,lineDashStyle: [3, 2],visibleInLegend: false }, //Out
 
6: { color: '#0A5EFA' }, //Frez
 
7: { color: '#0A5EFA',lineWidth:2,lineDashStyle: [3, 2],visibleInLegend: false }, //Frez
 
8: { color: '#44B8F2' },  //Frig
 
9: { color: '#44B8F2',lineWidth:2,lineDashStyle: [3, 2],visibleInLegend: false }  //Frig
  
},

 hAxis
: {
 titleTextStyle
: {fontSize: 14},
 gridlines
: {count: hMaj},
 minorGridlines
: {count: hMnr},
 ticks
: hTicks
 
},
 vAxis
: {
 title
: vAxisString,
 titleTextStyle
: {fontSize: 14},
 gridlines
: {count: vMaj},
 minorGridlines
: {count: vMnr},
 ticks
: vTicks
 
}
 
};
// Other Chart Visualizations can be readily substituted for the LineChart visualization. Column or Area are almost interchangeable with the Line Charts.
// See the Google documentation at ... https://developers.google.com/chart/interactive/docs/gallery for details.
 
var chart = new google.visualization.LineChart(document.getElementById(divName));
 chart
.draw(view,options);
 
});
} </script>
</head>

  
<body>
<!--  The Google DAY Chart is drawn below plus my old "LogTemp" App charts (WEEK/MONTH) which I haven't converted yet. -->
    
<div id="dayChart" style="width: 625px; height: 340px;"></div>
 
<div id="weekChart" style="width: 625px; height: 340px;"></div>
 
<div id="monthChart" style="width: 625px; height: 340px;"></div>
  
</body>
</html>


chartTemps.html


댓글 없음:

댓글 쓰기