Showing posts with label Data Visualization. Show all posts
Showing posts with label Data Visualization. Show all posts

Thursday, January 1, 2015

D3: Simple javascript class wrapper for Association Graph

This is a simple javascript class wrapper (in both css and js) for the Association Graph Visualization at http://wimbledon.prcweb.co.uk/davidgoliath.html, The interface separates json data, html element, and the actual HeroGraphPlot class. It is modified so that it will be easier for a web developer to easily add a association graph chart into their application.

Below is the link to the source code (remember to put in in the web folder of a web server such as xamp so that the html page will be able to download the json in the same folder):

https://dl.dropboxusercontent.com/u/113201788/d3/assoc-graph.zip

Below is the html which includes the javascript that download a json data and then display as a HeroGraphPlot chart:

<html>
<head>

<link href="lib/herograph.css" rel="stylesheet"></link>

<script src="lib/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="lib/d3.min.js" type="text/javascript"></script>
<script src="lib/underscore-min.js" type="text/javascript"></script>
<script src="lib/herograph.js" type="text/javascript"></script>

<script>
$(function(){
 plotBiPartite();
});
function plotBiPartite()
{
 d3.json("herograph.json", function(graphData) {
  var plot = new HeroGraphPlot("chart", "info", graphData);
 });
}
</script>
<style>
body{
padding-top: 10px;
}
</style>
</head>
<body>
    <svg id="chart" class="herograph">
    <defs>
       <marker id="Triangle"
         refX="0" refY="3" 
         markerUnits="strokeWidth"
         markerWidth="6" markerHeight="6"
         orient="auto">
         <path d="M 0 0 L 6 3 L 0 6 z" />
       </marker>
     </defs>
   </svg>

   <div id="info" class="herographinfo"></div>
</body>
</html>


D3: Simple javascript class wrapper for Concept Map

This is a simple javascript class wrapper (in both css and js) for the Concept Map Visualization at http://www.findtheconversation.com/concept-map/, The interface separates json data, html element, and the actual ConceptMap class. It is modified so that it will be easier for a web developer to easily add a concept map chart into their application.

Below is the link to the source code (remember to put in in the web folder of a web server such as xamp so that the html page will be able to download the json in the same folder):

https://dl.dropboxusercontent.com/u/113201788/d3/concept-map.zip

Below is the html which includes the javascript that download a json data and then display as a ConceptMap chart:

<html>
<head>

<link href="lib/concept-map.css" rel="stylesheet"></link>

<script src="lib/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="lib/d3.min.js" type="text/javascript"></script>
<script src="lib/packages.js" type="text/javascript"></script>
<script src="lib/concept-map.js" type="text/javascript"></script>

<script>
$(function(){
 plotConceptMap();
});
function plotConceptMap()
{
 d3.json("metadata.json", function(dataJson) {
  var plot = new ConceptMap("graph", "graph-info", dataJson);
 });
}
</script>
<style>
body{
padding-top: 10px;
}
</style>
</head>
<body>
    <div id="graph" class="conceptmap" ></div>
    <div id="graph-info"></div>
</body>
</html>


Bootstrap: Center charts in bootstrap panel

To center charts in bootstrap panel, add "style='text-align:center'" to the div element of the panel-body. Below is the code snippet:

<div class="row" style="padding-top:10px">
	<div class="col-md-4">
		<div class="panel panel-primary">
			<div class="panel-heading">C3 Gauge</div>
			<div class="panel-body" style="text-align:center">
				<div id="chtGaugeC3"></div>
			</div>
		
		</div>
	</div>
	
	<div class="col-md-4">
		<div class="panel panel-primary">
			<div class="panel-heading">D3 Gauge</div>
			<div class="panel-body" style="text-align:center">
				<div id="chtGaugeD3"></div>
			</div>
		</div>
	</div>
	
	<div class="col-md-4">
		<div class="panel panel-primary">
			<div class="panel-heading">C3 Gauge</div>
			<div class="panel-body" style="text-align:center">
				<div id="chtGauge"></div>
			</div>
		</div>
	</div>
</div>

Below is the link some examples of charts such as Hive Plot, gauge in bootstrap:

https://dl.dropboxusercontent.com/u/113201788/d3/charts-with-bootstrap-panel.zip

D3: Simple javascript class wrapper for Matrix Diagram

This is a simple javascript class wrapper (in both css and js) for the Matrix Diagram Visualization at http://bost.ocks.org/mike/hive/, The interface separates json data, html element, and the actual MatrixPlot class. It is modified so that it will be easier for a web developer to easily add a bipartite chart into their application.

Below is the link to the source code (remember to put in in the web folder of a web server such as xamp so that the html page will be able to download the json in the same folder):

https://dl.dropboxusercontent.com/u/113201788/d3/matrix.zip

Below is the html which includes the javascript that download a json data and then display as a MatrixPlot chart:

<html>
<head>

<link href="lib/matrix-plot.css" rel="stylesheet"></link>

<script src="lib/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="lib/d3.min.js" type="text/javascript"></script>
<script src="lib/packages.js" type="text/javascript"></script>
<script src="lib/matrix-plot.js" type="text/javascript"></script>

<script>
$(function(){
	plotMatrix();
});

function plotMatrix()
{
	d3.json("miserables.json", function(miserables) {
		var plot = new MatrixPlot("chtMatrix", 'order', miserables);
	});
}
</script>
<style>
body{
padding-top: 10px;
padding-left: 60px;
}
</style>
</head>
<body>
				<p>Order: <select id="order">
				  <option value="name">by Name</option>
				  <option value="count">by Frequency</option>
				  <option value="group">by Cluster</option>
				</select>
				</p>
				
				<br />
				
				<div id="chtMatrix" class="matrixplot" ></div>
</div>


</div>
</body>
</html>


D3: Simple javascript class wrapper for Sankey Plot

This is a simple javascript class wrapper (in both css and js) for the Sankey Plot Visualization at http://bl.ocks.org/billierinaldi/raw/3779574/, The interface separates json data, html element, and the actual SankeyPlot class. It is modified so that it will be easier for a web developer to easily add a bipartite chart into their application.

Below is the link to the source code (remember to put in in the web folder of a web server such as xamp so that the html page will be able to download the json in the same folder):

https://dl.dropboxusercontent.com/u/113201788/d3/sankey.zip

Below is the html which includes the javascript that download a json data and then display as a SankeyPlot chart:

<html>
<head>
<link href="lib/sankey-plot.css" rel="stylesheet"></link>

<script src="lib/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="lib/d3.min.js" type="text/javascript"></script>
<script src="lib/sankey.js" type="text/javascript"></script>
<script src="lib/sankey-plot.js" type="text/javascript"></script>

<script>
$(function(){
 plotSankey();
});

function plotSankey()
{
 d3.json("energy.json", function(energy) {
  var plot = new SankeyPlot("chtSankey", energy);
 });
}
</script>
<style>
body{
padding-top: 10px;
}
</style>
</head>
<body>
<div id="chtSankey" class="sankeyplot" ></div>  
</body>
</html>


D3: Simple javascript class wrapper for Hive Plot

This is a simple javascript class wrapper (in both css and js) for the Hive Plot Visualization at http://bost.ocks.org/mike/hive/, The interface separates json data, html element, and the actual HivePlot class. It is modified so that it will be easier for a web developer to easily add a hive plot chart into their application.

Below is the link to the source code (remember to put in in the web folder of a web server such as xamp so that the html page will be able to download the json in the same folder):

https://dl.dropboxusercontent.com/u/113201788/d3/hive-plot.zip

Below is the html which includes the javascript that download a json data and then display as a HivePlot chart:

<html>
<head>

<link href="lib/hive-plot.css" rel="stylesheet"></link>

<script src="lib/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="lib/d3.min.js" type="text/javascript"></script>

<script src="lib/hive-plot.js" type="text/javascript"></script>

<script>
$(function(){
 plotHive();
});

function plotHive()
{
 var url = "flare-imports.json";
 // Load the data and display the plot!
 d3.json(url, function(nodes) {
  var plot = new HivePlot("chtHivePlot", "infoHivePlot", nodes);
 });
}
</script>
<style>
body{
padding-top: 10px;
}
</style>
</head>
<body>
<div id="chtHivePlot" class="hiveplot" ></div>
</body>
</html>


D3: Simple javascript class wrapper for Hierarchical Edge Bundling Visualization

This is a simple javascript class wrapper (in both css and js) for the Hierarchical Edge Bundling Visualization at http://bl.ocks.org/mbostock/1044242, The interface separates json data, html element, and the actual HierarchicalEdgeBundling class. It is modified so that it will be easier for a web developer to easily add a hierarchical edge bundling chart into their application.

Below is the link to the source code (remember to put in in the web folder of a web server such as xamp so that the html page will be able to download the json in the same folder):

https://dl.dropboxusercontent.com/u/113201788/d3/hierarchical-edge-bundling.zip

Below is the html which includes the javascript that download a json data and then display as a HierarchicalEdgeBundling chart:

<html>
<head>

<link href="lib/hierarchical-edge-bundling.css" rel="stylesheet"></link>

<script src="lib/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="lib/d3.min.js" type="text/javascript"></script>
<script src="lib/packages.js" type="text/javascript"></script>
<script src="lib/hierarchical-edge-bundling.js" type="text/javascript"></script>

<script>
$(function(){
 plotHierarchicalEdgeBundling();
});

function plotHierarchicalEdgeBundling()
{
 d3.json("readme-flare-imports.json", function(data) {
  var plot = new HierarchicalEdgeBundling("chtHierarchicalEdgeBundling", "infoHierarchicalEdgeBundling", data);
 });
}
</script>
<style>
body{
padding-top: 10px;
}
</style>
</head>
<body>
<div id="chtHierarchicalEdgeBundling" class="heb"></div>
</body>
</html>


D3: Simple javascript wrapper class for Collapsible Tree

This is a simple javascript class wrapper (in both css and js) for the Collapse Tree Visualization at http://mbostock.github.io/d3/talk/20111018/tree.html, The interface separates json data, html element, and the actual CollapsibleTree class. It is modified so that it will be easier for a web developer to easily add a collapsible tree chart into their application.

Below is the link to the source code (remember to put in in the web folder of a web server such as xamp so that the html page will be able to download the json in the same folder):

https://dl.dropboxusercontent.com/u/113201788/d3/collapsible-tree.zip

Below is the html which includes the javascript that download a json data and then display as a CollapsibleTree chart:

<html>
<head>

<link href="lib/collapsible-tree.css" rel="stylesheet"></link>

<script src="lib/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="lib/d3.min.js" type="text/javascript"></script>
<script src="lib/collapsible-tree.js" type="text/javascript"></script>

<script>
$(function(){
 plotCollasiableTree();
});

function plotCollasiableTree()
{
 d3.json("flare.json", function(json) {
  var plot = new CollapsibleTree("chtCollapsibleTree", json);
 });
}

</script>
<style>
body{
padding-top: 10px;
}
</style>
</head>
<body>
<div id="chtCollapsibleTree" class="collapsibletree" ></div>
</body>
</html>



D3: Simple wrapper class for BiPartite Visualization

This is a simple javascript class wrapper (in both css and js) for the BiPartite Visualization at http://bl.ocks.org/NPashaP/9796212, The interface separates json data, html element, and the actual biPartitePlot class. It is modified so that it will be easier for a web developer to easily add a bipartite graph into their application.

Below is the link to the source code (remember to put in in the web folder of a web server such as xamp so that the html page will be able to download the json in the same folder):


Below is the html which includes the javascript that download a json data and then display as a BiPartite chart:

<html>
<head>


<script src="lib/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="lib/d3.min.js" type="text/javascript"></script>
<script src="lib/packages.js" type="text/javascript"></script>
<script src="lib/biPartite.js" type="text/javascript"></script>
<script src="lib/biPartite-plot.js" type="text/javascript"></script>

<script>
$(function(){
 plotBiPartite();
});
function plotBiPartite()
{
 d3.json("sales_data.json", function(sales_data) {
  var plot = new biPartitePlot("chtBiPartite");
  var data = [ 
  {data: plot.partData(sales_data,2), id:'SalesAttempts', header:["Channel","State", "Sales Attempts"]},
  {data: plot.partData(sales_data,3), id:'Sales', header:["Channel","State", "Sales"]}
  ];
  plot.draw(data);
 });
}
</script>
<style>
body{
padding-top: 10px;
}
</style>
</head>
<body>
<div id="chtBiPartite" class="bipartite" ></div>
</body>
</html>

D3: Simple Javascript class wrapper for Gauge

Below is the link for the source code which makes some minor modification over the gauge implementation in D3 (please refers to http://bl.ocks.org/tomerd/1499279) so that it is easier for me to use:

https://dl.dropboxusercontent.com/u/113201788/d3/gauge.zip

The web page codes below shows how to use it:

<html>
<head>

<link href="lib/c3.css" rel="stylesheet"></link>

<script src="lib/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="lib/d3.min.js" type="text/javascript"></script>
<script src="lib/gauge.js" type="text/javascript"></script>

<script>
$(function(){
 createC3Gauge('chtGaugeC3', 'sentiment', 91.4, 200, 180);
 var gaugeD3 = createD3Gauge('chtGaugeD3', 'sentiment', 200);
 gaugeD3.redraw(91.4);
});

function createD3Gauge(chartElementId, label, chartWidth)
{
 var config = 
 {
  size: chartWidth,
  label: label,
  min: 0,
  max: 100,
  minorTicks: 5
 }
 
 var range = config.max - config.min;
 config.yellowZones = [{ from: config.min + range*0.75, to: config.min + range*0.9 }];
 config.redZones = [{ from: config.min + range*0.9, to: config.max }];
 
 gaugeD3 = new Gauge(chartElementId, config);
 gaugeD3.render();
 
 return gaugeD3;
}
</script>
<style>
body{
padding-top: 10px;
}
</style>
</head>
<body>
<div id="chtGaugeD3"></div>
</body>
</html>

Thursday, December 18, 2014

C3: Create a Pie Chart with specific width and height

Below is the code snippet to create a pie chart with specific with and height, using C3 data visualization library:

<div id="pieChart"></div>

<script>
var chart = c3.generate({
bindto : '#pieChart',
size: {
width: 300,
height: 300
},
   data: {
       columns: [
['data1' : 45],
['data2' : 56],
['data3' : 20]
],
       type : 'pie'
   }
});
</script>

Wednesday, December 17, 2014

C3: Formatting for yyyy-MM-dd HH:mm:ss for the timeseries

This simple step in C3 cracked my head a bit, therefore i like to write it down for future reference. Basically, I have a piece of json data containing the following two fields:

  • date
  • rate
I like the x axis of a C3 time series chart to display the date values in the json, the format of the date values is as follows:

yyyy-MM-dd HH:mm:ss

My original javascript looks like the following:

<link href="./c3.min.css" rel="stylesheet" type="text/css">
<script src="./d3.min.js"></script>
<script src="./c3.min.js"></script>
<script src="./d3.tip.v0.6.3.js"></script>
<script src="./jquery-1.8.3.min.js"></script>

<script type="text/javascript">
 $(function(){
$.ajax({
            url        : "jsonData.php",
            type       : "GET",
            data       : post_data,
            dataType : "json",
            success    : function(returned_data)
            {
                console.log(returned_data);
               
                var column_date = returned_data.date;
                var column_val = returned_data.sample;
               
                console.log(column_date);
                console.log(column_val);
               
                column_date.unshift('date');
                column_val.unshift('sample');
               
                var chart = c3.generate({
                    data: {
                        x : 'date',
                        columns : [
                            column_date,
                            column_val
                        ]
                    },
                    bindto: '#timeSeriesChart',
                    axis: {
                        x: {
                            type: 'timeseries',
                        }
                    }                });
            }
        });

});
</script>

After trying out various configuration that do not work, i finally stumbled on one solution that works, which is to add a "xFormat : '%Y-%m-%d %H:%M:%S'", that is as follows:

$(function(){
$.ajax({
            url        : "jsonData.php",
            type       : "GET",
            data       : post_data,
            dataType : "json",
            success    : function(returned_data)
            {
                console.log(returned_data);
               
                var column_date = returned_data.date;
                var column_val = returned_data.sample;
               
                console.log(column_date);
                console.log(column_val);
               
                column_date.unshift('date');
                column_val.unshift('sample');
               
                var chart = c3.generate({
                    data: {
                        x : 'date',
                        xFormat : '%Y-%m-%d %H:%M:%S',
                        columns : [
                            column_date,
                            column_val
                        ]
                    },
                    bindto: '#timeSeriesChart',
                    axis: {
                        x: {
                            type: 'timeseries',
                        }
                    }                });
            }
        });

}); 

Another thing to note is that the settings of x axis tick label can be done by adding the following to the "axis" element (if the time value is too long, you can add a "rotate: 45" to the "tick" below):

 tick: {
        format: '%H:%M:%S'
 }


for example:

 
$(function(){
$.ajax({
            url        : "jsonData.php",
            type       : "GET",
            data       : post_data,
            dataType : "json",
            success    : function(returned_data)
            {
                console.log(returned_data);
               
                var column_date = returned_data.date;
                var column_val = returned_data.sample;
               
                console.log(column_date);
                console.log(column_val);
               
                column_date.unshift('date');
                column_val.unshift('sample');
               
                var chart = c3.generate({
                    data: {
                        x : 'date',
                        xFormat : '%Y-%m-%d %H:%M:%S',
                        columns : [
                            column_date,
                            column_val
                        ]
                    },
                    bindto: '#timeSeriesChart',
                    axis: {
                        x: {
                            type: 'timeseries',


 tick: {
        format: '%H:%M:%S'
 }


                        }
                    }                });
            }
        });

}); 

Tuesday, July 16, 2013

Getting JqPlot to work inside a JQuery UI Tab

Jqplot is a very simple jquery-based plotting library for displaying simple plotting charts on html page, however, having a jqplot <div> in a jquery ui container such as tab and not having it displayed as default (e.g. having the jqplot as the second tab page instead of the default first tab page), the jqplot <div> will not display any plot. For example the following code will not work for the jqplot:

<html>
<head>
<link rel="stylesheet" type="text/css" href="jquery-ui/themes/base/jquery.ui.all.css">
<link rel="stylesheet" type="text/css" href="jquery-ui/demos.css">
<link rel="stylesheet" type="text/css" href="jqplot/jquery.jqplot.min.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="jqplot/jquery.jqplot.min.js"></script>
<script type="text/javascript" src="jqplot/plugins/jqplot.barRenderer.min.js"></script>
<script type="text/javascript" src="jqplot/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script type="text/javascript" src="jqplot/plugins/jqplot.pieRenderer.min.js"></script>
<script type="text/javascript" src="jqplot/plugins/jqplot.pointLabels.min.js"></script>
<script src="jquery-ui/ui/jquery.ui.core.js"></script>
<script src="jquery-ui/ui/jquery.ui.widget.js"></script>
<script src="jquery-ui/ui/jquery.ui.tabs.js"></script>
<script type="text/javascript">
$(function(){
$( "#tabs" ).tabs();

    var s1 = [1, 2, 3];
    // Can specify a custom tick Array.
    // Ticks should match up one for each y value (category) in the series.
    var ticks = ["Val1", "Val2", "Val3"];
     
    var plot1 = $.jqplot('chart1', [s1], {
        // The "seriesDefaults" option is an options object that will
        // be applied to all series in the chart.
        seriesDefaults:{
            renderer:$.jqplot.BarRenderer,
            rendererOptions: {fillToZero: true}
        },
        // Custom labels for the series are specified with the "label"
        // option on the series option.  Here a series option object
        // is specified for each series.
        series:[
            {label:'Search Query'}
        ],
        // Show the legend and put it outside the grid, but inside the
        // plot container, shrinking the grid to accomodate the legend.
        // A value of "outside" would not shrink the grid and allow
        // the legend to overflow the container.
        legend: {
            show: true,
            placement: 'outsideGrid'
        },
        axes: {
            // Use a category axis on the x axis and use our custom ticks.
            xaxis: {
                renderer: $.jqplot.CategoryAxisRenderer,
                ticks: ticks
            },
            // Pad the y axis just a little so bars can get close to, but
            // not touch, the grid boundaries.  1.2 is the default padding.
            yaxis: {
                pad: 1.05,
                tickOptions: {formatString: '%d'}
            }
        }
    });
var s2 = [["Val1":1], ["Val2":2], ["Val3":3]];
         
    var plot2 = $.jqplot('pie', [s2], {
        grid: {
            drawBorder: false, 
            drawGridlines: false,
            background: '#ffffff',
            shadow:false
        },
        axesDefaults: {
             
        },
        seriesDefaults:{
            renderer:$.jqplot.PieRenderer,
            rendererOptions: {
                showDataLabels: true
            }
        },
        legend: {
            show: true,
            rendererOptions: {
                numberRows: 1
            },
            location: 's'
        }
    }); 
$('#tabs').bind('tabsshow', function(event, ui) {
 if (ui.index === 1 && plot1._drawCount === 0) {
plot1.replot();
 }
 else if (ui.index === 2 && plot2._drawCount === 0) {
plot2.replot();
 }
});

});
</script>
</head>
<body>
<div id="tabs" style="min-height:500px">
<ul>
<li><a href="#tabs-1">Tabular Data</a></li>
<li><a href="#tabs-2">Histogram</a></li>
<li><a href="#tabs-3">Pie Chart</a></li>
</ul>
       <div id="tabs-1">
First Tab Page
</div>
<div id="tabs-2">
<div id="chart1" data-height="480px" data-width="960px" style="margin-top:20px; margin-left:20px;"></div>
</div>
<div id="tabs-3">
<div id="pie" data-height="480px" data-width="960px" style="margin-top:20px; margin-left:20px;"></div>
</div>
</div>
</body>
</html>

The solution is to call the jqplot element's replot() method when a tab page is selected by adding the highlighted section shown below:

<html>
<head>
<link rel="stylesheet" type="text/css" href="jquery-ui/themes/base/jquery.ui.all.css">
<link rel="stylesheet" type="text/css" href="jquery-ui/demos.css">
<link rel="stylesheet" type="text/css" href="jqplot/jquery.jqplot.min.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="jqplot/jquery.jqplot.min.js"></script>
<script type="text/javascript" src="jqplot/plugins/jqplot.barRenderer.min.js"></script>
<script type="text/javascript" src="jqplot/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script type="text/javascript" src="jqplot/plugins/jqplot.pieRenderer.min.js"></script>
<script type="text/javascript" src="jqplot/plugins/jqplot.pointLabels.min.js"></script>
<script src="jquery-ui/ui/jquery.ui.core.js"></script>
<script src="jquery-ui/ui/jquery.ui.widget.js"></script>
<script src="jquery-ui/ui/jquery.ui.tabs.js"></script>
<script type="text/javascript">
$(function(){
$( "#tabs" ).tabs();

    var s1 = [1, 2, 3];
    // Can specify a custom tick Array.
    // Ticks should match up one for each y value (category) in the series.
    var ticks = ["Val1", "Val2", "Val3"];
     
    var plot1 = $.jqplot('chart1', [s1], {
        // The "seriesDefaults" option is an options object that will
        // be applied to all series in the chart.
        seriesDefaults:{
            renderer:$.jqplot.BarRenderer,
            rendererOptions: {fillToZero: true}
        },
        // Custom labels for the series are specified with the "label"
        // option on the series option.  Here a series option object
        // is specified for each series.
        series:[
            {label:'Search Query'}
        ],
        // Show the legend and put it outside the grid, but inside the
        // plot container, shrinking the grid to accomodate the legend.
        // A value of "outside" would not shrink the grid and allow
        // the legend to overflow the container.
        legend: {
            show: true,
            placement: 'outsideGrid'
        },
        axes: {
            // Use a category axis on the x axis and use our custom ticks.
            xaxis: {
                renderer: $.jqplot.CategoryAxisRenderer,
                ticks: ticks
            },
            // Pad the y axis just a little so bars can get close to, but
            // not touch, the grid boundaries.  1.2 is the default padding.
            yaxis: {
                pad: 1.05,
                tickOptions: {formatString: '%d'}
            }
        }
    });
var s2 = [["Val1":1], ["Val2":2], ["Val3":3]];
         
    var plot2 = $.jqplot('pie', [s2], {
        grid: {
            drawBorder: false, 
            drawGridlines: false,
            background: '#ffffff',
            shadow:false
        },
        axesDefaults: {
             
        },
        seriesDefaults:{
            renderer:$.jqplot.PieRenderer,
            rendererOptions: {
                showDataLabels: true
            }
        },
        legend: {
            show: true,
            rendererOptions: {
                numberRows: 1
            },
            location: 's'
        }
    }); 
$('#tabs').bind('tabsshow', function(event, ui) {
  if (ui.index === 1 && plot1._drawCount === 0) {
plot1.replot();
  }
  else if (ui.index === 2 && plot2._drawCount === 0) {
plot2.replot();
  }
});

});
</script>
</head>
<body>
<div id="tabs" style="min-height:500px">
<ul>
<li><a href="#tabs-1">Tabular Data</a></li>
<li><a href="#tabs-2">Histogram</a></li>
<li><a href="#tabs-3">Pie Chart</a></li>
</ul>
       <div id="tabs-1">
First Tab Page
</div>
<div id="tabs-2">
<div id="chart1" data-height="480px" data-width="960px" style="margin-top:20px; margin-left:20px;"></div>
</div>
<div id="tabs-3">
<div id="pie" data-height="480px" data-width="960px" style="margin-top:20px; margin-left:20px;"></div>
</div>
</div>
</body>
</html>

Surface Map in C# winforms using ChartDirector

The following code shows how to plot a surface map (similar to the one in MATLab) in C# winform using ChartDirector (The data to be displayed is stored in a matrix):

private void UpdatePrimitiveFitnessSurfaceMapByData(WinChartViewer viewer, List<double[]> matrix)
        {
            int dim1 = matrix.Count;
            if (dim1 == 0) return;
            int dim2 = matrix[0].Length;

            // The x and y coordinates of the grid
            double[] dataX = new double[dim1];
            double[] dataY = new double[dim2];

            for (int i = 0; i < dim1; ++i)
            {
                dataX[i] = i;
            }
            for (int i = 0; i < dim2; ++i)
            {
                dataY[i] = i;
            }

            double[] dataZ = new double[(dataX.Length) * (dataY.Length)];
            for (int i = 0; i < dim1; ++i)
            {
                for (int j = 0; j < dim2; ++j)
                {
                    dataZ[i * dim2 + j] = matrix[i][j];
                }
            }

            // Create a SurfaceChart object of size 720 x 600 pixels
            SurfaceChart c = new SurfaceChart(720, 600);

            // Add a title to the chart using 20 points Times New Roman Italic font
            c.addTitle("Variable Fitness Distribution", "Times New Roman Italic", 20);

            // Set the center of the plot region at (350, 280), and set width x depth
            // x height to 360 x 360 x 270 pixels
            c.setPlotRegion(350, 280, 360, 360, 270);

            // Set the data to use to plot the chart
            c.setData(dataX, dataY, dataZ);

            // Spline interpolate data to a 80 x 80 grid for a smooth surface
            c.setInterpolation(80, 80);

            // Add a color axis (the legend) in which the left center is anchored at
            // (645, 270). Set the length to 200 pixels and the labels on the right
            // side.
            c.setColorAxis(645, 270, Chart.Left, 200, Chart.Right);

            // Set the x, y and z axis titles using 10 points Arial Bold font
            c.xAxis().setTitle("Generation", "Arial Bold", 10);
            c.yAxis().setTitle("Terminal Variable Index", "Arial Bold", 10);
            c.zAxis().setTitle("Variable Fitness Distribution",
                "Arial Bold", 10);

            // Output the chart
            viewer.Chart = c;
        }

Tuesday, July 9, 2013

Step-by-step for installing QwtPlot on Ubuntu Linux

Step 1: Install g++
Check whether g++ compiler has been installed on the target Linux machine by entering the following in the command prompt:
$g++

If the target Linux machine indicates no g++ compiler is installed on the machine, proceed to install the compiler by entering the following in the command prompt:
$sudo apt-get install g++

Step 2: Install CMake
Check whether cmake has been installed on the target linux machine, by entering the following in the command prompt:
$cmake -help

If the target linux machine indicates no cmake is installed on the machine, proceed to install cmake by entering the following in the command prompt:
$sudo apt-get install cmake


Step 3: Install Qt
Check whether Qt has been installed on the target linux machine, by entering the following in the command prompt:
$qmake -help

If the target linux machine indicates no Qt is installed on the machine, proceed to install Qt by entering the following in the command prompt:
$sudo apt-get install libqt4-dev qt4-dev-tools

Step 4: Install QwtPlot
To install QwtPlot, download the software package qwt-6.0.1.zip from 

Unzip the package (to unzip, if you are using Ubuntu, right-click the zip file and click "Extract Here" from the context menu). Next from the terminal, cd to the unzipped folder "qwt-6.0.1", and run the following command:
$qmake
This will generate the Makefile require to build QwtPlot, next run the command:
$make
This will build the QwtPlot, next run the command:
$sudo make install
This will install QwtPlot (when using ubuntu, the installed directory can be found at usr/local/qwt-6.0.1). The final step is to add the QwtPlot export statement into the .bashrc file in the /home/[username] directory ([username] refers to the linux login id). To add the export statement, run the following commands in the terminal:
$cd /home/[username]
$ls -a
$gedit .bashrc
In the .bashrc file that opened, add the following two lines to the bottom of the file
export QWT=/usr/local/qwt-6.0.1
export LD_LIBRARY_PATH=$QWT/lib:$LD_LIBRARY_PATH

Step 5: Build Qt application using QwtPlot
To build the Qt application with QwtPlot data visualization, enter the following command with the  Qt project folder:
$qmake -project

This will build the xxx.pro (where xxx refers to the project name), in the xxx.pro, just below the line starting wtih "INCLUDEPATH" (or below the line starting with "TARGET=" if line starting with "INCLUDEPATH"  is not in xxx.pro), insert the following lines:
QWT_VER_MAJ      = 6
QWT_VER_MIN      = 0
QWT_VER_PAT      = 1
QWT_VERSION      = $${QWT_VER_MAJ}.$${QWT_VER_MIN}.$${QWT_VER_PAT}

QWT_DIR = /usr/local/qwt-$$QWT_VERSION 

LIBS += -L$$QWT_DIR/lib -lqwt
INCLUDEPATH += $$QWT_DIR/include

Now run the following command to build the project
$qmake
$make


Friday, July 5, 2013

Create 3D Pie Chart in Winforms

This post shows how to create 3D Pie Chart in Winforms using ChartDirector (http://www.advsofteng.com/),

        private void CreatePieChart(WinChartViewer viewer, string title, double[] data, string[] data_labels)
        {
            int width = viewer.Width;
            int height = viewer.Height;

            PieChart c = new PieChart(width, height);


            c.setPieSize(width / 2, height / 2, System.Math.Max(System.Math.Min(width / 2 - 40, height / 2 - 40), 100));


            c.addTitle(title);

            c.set3D();

            c.setSectorStyle(Chart.RoundedEdgeShading, 0xffffff, 1);


            // Set the pie data and the pie labels

            c.setData(data, data_labels);
            // Output the chart
            viewer.Chart = c;
            viewer.ImageMap = c.getHTMLImageMap("clickable", "",
                "title='{label}: {value} ({percent}%)'");
        }

Create 3D Scatter Chart for Winform

There are some tutorial on CodeProject that shows how to create 3D scatter chart (e.g. the one frequently seen in MATLAB), but they are quite primitive. ChartDirector (http://www.advsofteng.com/) seems to offer an excellent solution for this. Below is the piece of code that adds a 3D scatter chart to a ChartDirector win chart viewer after it is added to a Winform:

public void Create3DScatterChart(WinChartViewer viewer, string title, List<Point> plot, int width, int height)
{
try
{
ThreeDScatterChart c = new ThreeDScatterChart(width, height);

c.addTitle(title, "Times New Roman Italic", 10);

c.setPlotRegion(width / 2 - 10, height / 2 - 15, width / 2, width / 2, height / 2 - 10);

c.setViewAngle(15, 30);

c.addLegend(width - 60, height - 180);

double[] xData=new double[plots.Count];
double[] yData=new double[plots.Count];
double[] zData=new double[plots.Count];
for(int i=0; i < plot.Count; ++i)
{
xData[i] = plot[i].X;
yData[i] = plot[i].Y;
zData[i] = plot[i].Z;
}

ThreeDScatterGroup g = c.addScatterGroup(xData, yData, zData, 
"Legend1",
ChartDirector.Chart.GlassSphere2Shape, 13, 
0xFF0000);
g.setLegendIcon(15, 15, 0xFF0000);

// Set the x, y and z axis titles using 10 points Arial Bold font
c.xAxis().setTitle("X", "Arial Bold", 10);
c.yAxis().setTitle("Y", "Arial Bold", 10);
c.zAxis().setTitle("Z", "Arial Bold", 10);

// Output the chart
viewer.Chart = c;


//include tool tip for the chart
viewer.ImageMap = c.getHTMLImageMap("clickable", "", "title='(X={x|p}, Y={y|p}, Z={z|p})'");
}
catch
{

}
}

To instead save the scatter 3d plot to a file, use the following code:

public void Create3DScatterChart(string filename, string title, List<Point> plot, int width, int height)
{
try
{
ThreeDScatterChart c = new ThreeDScatterChart(width, height);

c.addTitle(title, "Times New Roman Italic", 10);

c.setPlotRegion(width / 2 - 10, height / 2 - 15, width / 2, width / 2, height / 2 - 10);

c.setViewAngle(15, 30);

c.addLegend(width - 60, height - 180);

double[] xData=new double[plots.Count];
double[] yData=new double[plots.Count];
double[] zData=new double[plots.Count];
for(int i=0; i < plot.Count; ++i)
{
xData[i] = plot[i].X;
yData[i] = plot[i].Y;
zData[i] = plot[i].Z;
}

ThreeDScatterGroup g = c.addScatterGroup(xData, yData, zData, 
"Legend1",
ChartDirector.Chart.GlassSphere2Shape, 13, 
0xFF0000);
g.setLegendIcon(15, 15, 0xFF0000);

// Set the x, y and z axis titles using 10 points Arial Bold font
c.xAxis().setTitle("X", "Arial Bold", 10);
c.yAxis().setTitle("Y", "Arial Bold", 10);
c.zAxis().setTitle("Z", "Arial Bold", 10);

// Output the chart
using(Image img=c.makeImage())
  {
      img.Save(filename);
   }


}
catch
{

}
}