365日アプリケーションブログ

一日一アプリケーションを構築することを目指すブログです。アプリケーションの種類は基本的に気まぐれです。

【20140505】【jqPlot】Ajaxで取得したデータのグラフ化

お題

Ajaxで取得したjson形式のデータをjqPlotでグラフ化する

ソース

jqPlot_ajax_sample1.html

<!DOCTYPE html>
<html> 
<head>
  <meta charset="utf-8" >
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" > 
  <link rel="stylesheet" href="js/jqplot/jquery.jqplot.min.css"/> 
  <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
  <script src="js/jqplot/jquery.jqplot.min.js"></script>
  <script src="js/jqplot/plugins/jqplot.canvasTextRenderer.min.js"></script>
  <script src="js/jqplot/plugins/jqplot.canvasAxisLabelRenderer.min.js"></script>
  <script src="js/jqplot/plugins/jqplot.canvasAxisTickRenderer.min.js"></script>
  <script src="js/jqplot/plugins/jqplot.mobile.min.js"></script>
  <script src="js/jqplot/plugins/jqplot.cursor.min.js"></script>
  <script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
  <script src="js/custom-ajaxdata.js"></script>  
</head>
<body>
<div data-role="page" id="p-ajaxchart">
  <div data-role="header">
    <h1>Ajaxによるデータの読み込み</h1>
  </div>
  <div data-role="content">
    <div id="linechart-ajax"></div>
  </div>
</div>
</body>
</html>

custom-dateaxis.js

$.jqplot.config.enablePlugins = true;

var ajaxDataRenderer = function(url, plot, options) {
	var ret = null;
	$.ajax({
		async: false,
		url: url,
		dataType:"json",
		success: function(data) {
			ret = data;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			alert('読み込み失敗:' + errorThrown);
		}
	});
	return ret;
};

var opts = {
		title: 'グラフタイトルだよ',
		dataRenderer: ajaxDataRenderer,
		series: [
		  {
			  label:'データ1だよ',
			  showMaker:false
		  },
		  {
			  label:'データ2だよ',
			  showMaker:true
		  },
		],
		
		legend: {
			show:true,
			location:'ne',
		},
		
		axes: {
			xaxis: {
				label:'x軸だよ',
				labelRenderer:$.jqplot.CanvasAxisLabelRenderer,
				tickRenderer: $.jqplot.CanvasAxisTickRenderer,
				tickOptions:{angle:-45}
			},
			yaxis: {
				label:'y軸だよ',
				labelRenderer:$.jqplot.CanvasAxisLabelRenderer,
				tickRenderer: $.jqplot.CanvasAxisTickRenderer,
			}
		},
		cursor:{zoom:true}
};

$(document).on("pageshow", "#p-ajaxchart", function(e){
	plot = $.jqplot("linechart-ajax", "./ajaxdata.json", opts);
});

$(window).on("orientationchange", function(e){
	plot.replot;
});

$(document).on("pagehide", "#p-ajaxchart", function(e){
	plot.destroy();
});

URL

http://www4386up.sakura.ne.jp/itiapp/jqplotsample/jqPlot_ajax_sample1.html