ユーザ用ツール

サイト用ツール


サイドバー

このページの翻訳:



最近の更新



Tag Cloud

14_web:02_gruph_hightcharts.js

02 グラフ表示(Highcharts.js)

http://www.highcharts.com/

綺麗なグラフが簡単に作成できて、色々細かなカスタマイズも可能。

http://api.highcharts.com/highcharts#plotOptions.series.dataLabels.formatter

・グラフに吹き出しを出す
http://faltc.blogspot.jp/2013/04/highcharts-30-axistopixels.html

一般的なグラフ

    53	<script src="/js/highcharts/highstock.js" type="text/javascript" language="JavaScript"></script>
    54	<script type="text/javascript" language="JavaScript">
    55	    
    56	    $(document).ready(function (){
    57	
    58	        var jsonData = {};
    59	        var dataLength = {};
    60	        
    61	        // VM
    62	        var options = { 
    63	            chart: {
    64	                type: &#039;spline&#039;, // 柔らかいLine
    65	                backgroundColor: &#039;#ffffff&#039;,
    66	                plotBackgroundColor: &#039;#eeeeee&#039;,
    67	                borderRadius: 10,
    68	                borderWidth: 1,
    69	                borderColor: &#039;#dddddd&#039;,
    70	            },
    71	            legend: {
    72	                enabled: true,
    73	                align: &#039;right&#039;,
    74	                layout: &#039;vertical&#039;,
    75	                verticalAlign: &#039;top&#039;,
    76	                y: 100,
    77	            },
    78	            plotOptions: {
    79	                series: {
    80	                    animation: {
    81	                        duration: 5000
    82	                    }
    83	                },
    84	                spline: {
    85	                    lineWidth: 2, //lineの太さ
    86	                    states: {
    87	                        hover: {
    88	                            lineWidth: 3 //マウスオーバー時
    89	                        }
    90	                    }
    91	                }
    92	            },
    93	            tooltip: {
    94	                borderRadius: 5, // tooltipの角丸み
    95	                borderWidth: 1,
    96	            },
    97	
    98	            title: { text: &#039;ドメインごとのVM数の推移&#039; },
    99	            xAxis: {
   100	                type: &#039;datetime&#039;,
   101	            },
   102	            subtitle: { 
   103	                text: &#039;&#039; 
   104	            }, 
   105	            yAxis: { 
   106	                allowDecimals: false,
   107	                title: { 
   108	                    text: &#039;仮想サーバ数&#039; 
   109	                    }, 
   110	                startOnTick: false,
   111	                min: 0,
   112	            },
   113	            rangeSelector: {
   114	                selected: 0,
   115	            },
   116	            navigator: {
   117	                series: {
   118	                    includeInCSVExport: false
   119	                },
   120	            },
   121	            series: [
   122	            ],
   123	            exporting: {
   124	                csv: {
   125	                    dateFormat: &#039;%Y-%m-%d&#039;
   126	                }
   127	            },
   128	        };
   129	
   130	        function getData(url, graph_id ) { // ajaxでデータ取得
   131	            $.ajax({
   132	                url: url,
   133	                type: &#039;GET&#039;,
   134	                dataType: &#039;json&#039;,
   135	                data: {},
   136	                async: true,
   137	                cache: false,
   138	                success: function (data) {
   139	                    var chart = $( graph_id ).highcharts();
   140	                    jsonData = data;
   141	                    dataLength = data.length;
   142	                    jQuery.each(data, function ( key, val ) {
   143	                        chart.addSeries( val );
   144	                    });
   145	                },
   146	            });
   147	        }
   148	        
   149	        
   150	        Highcharts.setOptions({
   151	            global: { useUTC: false }
   152	        });
   153	
   154	        // 該当ドメインをクリックでグラフ表示
   155	        $(&#039;#domain .domainname&#039;).click(function(){
   156	                var graph_id = &#039;#domain_graph&#039;;
   157	                var id = $(this).attr(&#039;id&#039;);
   158	                console.log(id);
   159	                options.subtitle.text = id;
   160	                $( graph_id ).highcharts(&#039;StockChart&#039;, options);
   161	                $("body,html").animate({scrollTop:0},800); // topまでゆっくり上がる
   162	                getData(&#039;/api/cloudstack_domains/domain/&#039; + id, graph_id);
   163	        });

jsonデータ

[
{"name":"running","tooltip":{"valueSuffix":"\u53f0"},
"data":[[1551652805000,47],[1551768004000,50],[1551799230000,50],[1551885904000,53],[1552004224000,52],[1552059604000,52],[1552146004000,52],[1552232404000,55],[1552318804000,56],[1552405205000,56],[1552491604000,56],[1552578004000,56],[1552664404000,56],[1552750804000,56],[1552837205000,56],[1552923605000,59],[1553010004000,59],[1553096404000,58],[1553182805000,59],[1553269205000,59],[1553355604000,59],[1553442005000,59]]
},{
"name":"stopped","tooltip":{"valueSuffix":"\u53f0"},
"data":[[1551652805000,3],[1551768004000,3],[1551799230000,3],[1551885904000,3],[1552004224000,3],[1552059604000,3],[1552146004000,3],[1552232404000,3],[1552318804000,3],[1552405205000,3],[1552491604000,3],[1552578004000,4],[1552664404000,4],[1552750804000,4],[1552837205000,4],[1552923605000,4],[1553010004000,4],[1553096404000,4],[1553182805000,4],[1553269205000,4],[1553355604000,4],[1553442005000,4]]
},{
"name":"cpu","tooltip":{"valueSuffix":"\u500b"},
"data":[[1551652805000,66],[1551768004000,69],[1551799230000,69],[1551885904000,74],[1552004224000,73],[1552059604000,73],[1552146004000,73],[1552232404000,76],[1552318804000,77],[1552405205000,77],[1552491604000,77],[1552578004000,79],[1552664404000,79],[1552750804000,79],[1552837205000,79],[1552923605000,82],[1553010004000,82],[1553096404000,82],[1553182805000,83],[1553269205000,83],[1553355604000,85],[1553442005000,83]]
},{
"name":"memory","tooltip":{"valueSuffix":"G"},
"data":[[1551652805000,84],[1551768004000,96],[1551799230000,96],[1551885904000,102],[1552004224000,96],[1552059604000,96],[1552146004000,96],[1552232404000,99],[1552318804000,103],[1552405205000,103],[1552491604000,100],[1552578004000,102],[1552664404000,102],[1552750804000,102],[1552837205000,102],[1552923605000,128],[1553010004000,128],[1553096404000,126],[1553182805000,127],[1553269205000,127],[1553355604000,129],[1553442005000,127]]
}
]

Hightchartsメモ

グラフ

グラフのバーとデータ表を連動させる

<script type="text/javascript" language="JavaScript">
	
	$(document).ready(function (){

		var jsonData = { &#039;isolate&#039;: { &#039;vm&#039;: {}, &#039;ip&#039;: {} }, &#039;basic&#039;: { &#039;vm&#039;: {}, &#039;ip&#039;: {} } };
		var dataLength = { &#039;isolate&#039;: { &#039;vm&#039;: 1, &#039;ip&#039;: 1 }, &#039;basic&#039;: { &#039;vm&#039;: 1, &#039;ip&#039;: 1 } };
		
		// VM
		var options = { 
			&#039;vm&#039;: {
				chart: {
					type: &#039;line&#039;,
					events: {
						redraw: function() {
							var params = this.renderTo.id.split( &#039;_&#039; );
							if ( this.series.length == ( dataLength[ params[3] ][ params[2] ] + 1 ) ) {
	 							setDataTable( this.renderTo.id, jsonData[ params[3] ][ params[2] ] );
							}
						},
					},
				},
				legend: {
					enabled: true,
					layout: &#039;horizontal&#039;,
				},
				title: { text: &#039;各ホスト(HV)ごとのVM数の推移&#039; },
				xAxis: { 
					allowDecimals: false,
					type: &#039;datetime&#039;,
					dateTimeLabelFormats: {
						day: &#039;%m/%d&#039;,
						month: &#039;%Y/%m&#039;,
					},
					labels: {
	//					format: &#039;{value:%Y/%m/%d}&#039;,
	//					rotation: 45,
	//					align: &#039;left&#039;,
						},
	//				startOnTick: true,
					},
				yAxis: { 
					allowDecimals: false,
					title: { 
						text: &#039;仮想サーバ数&#039; 
						}, 
					startOnTick: false,
					min: 0,
					},
				rangeSelector: {
					selected: 0,
				},
				navigator: {
					series: {
						includeInCSVExport: false
					},
				},
				exporting: {
					csv: {
						dateFormat: &#039;%Y-%m-%d&#039;
					}
				},
			},
			&#039;ip&#039;: {
				chart: {
					type: &#039;area&#039;,
					events: {
						redraw: function() {
							var params = this.renderTo.id.split( &#039;_&#039; );
							if ( this.series.length == ( dataLength[ params[3] ][ params[2] ] + 1 ) ) {
	 							setDataTable( this.renderTo.id, jsonData[ params[3] ][ params[2] ] );
							}
						},
					},
				},
				legend: {
					enabled: true,
					layout: &#039;horizontal&#039;,
				},
				pilotOptions: {
					series: {
						stacking: &#039;normal&#039;,
					},
				},
				tooltip: {
					formatter: function() {
						var date = Highcharts.dateFormat("%Y/%m/%d", this.x);
						var s = &#039;<b>&#039; + date +&#039;</b>&#039;;
						var total = this.points[0].y;
						
						$.each(this.points, function ( i, point ) {
							var percent = Highcharts.numberFormat((point.y / total) * 100, 2);
							var strPercent = &#039;(&#039; + percent + &#039;%)&#039;
							s += &#039;<br />&#039; + point.series.name + &#039; : <b>&#039; + point.y + &#039;</b>&#039;;
							if ( i != 0 ) {
								s+= strPercent;
							}
						});
							
						return s;
					},
					shared: true
				},
				title: { text: &#039;グローバルIPの利用推移&#039; },
				xAxis: { 
					allowDecimals: false,
					type: &#039;datetime&#039;,
					dateTimeLabelFormats: {
						day: &#039;%m/%d&#039;,
						month: &#039;%Y/%m&#039;,
					},
					labels: {
	//					format: &#039;{value:%Y/%m/%d}&#039;,
	//					rotation: 45,
	//					align: &#039;left&#039;,
					},
	//				startOnTick: true,
				},
				yAxis: { 
					allowDecimals: false,
					title: { 
						text: &#039;グローバルIP数&#039; 
					}, 
				},
				rangeSelector: {
					selected: 0,
				},
			},
		};

		function getData(url, graph_id ) {
			$.ajax({
				url: url,
				type: &#039;GET&#039;,
				dataType: &#039;json&#039;,
				data: {},
				async: true,
				cache: false,
				success: function (data) {
					var chart = $( graph_id ).highcharts();
					var params = graph_id.split( &#039;_&#039; );
					jsonData[ params[3] ][ params[2] ] = data;
					dataLength[ params[3] ][ params[2] ] = data.length;
					
					jQuery.each(data, function ( key, val ) {
						chart.addSeries( val );
					});
				},
			});
		}
		
		
		Highcharts.setOptions({
			global: { useUTC: false }
		});

		var tabsOptions = {
				&#039;activate&#039;: function ( event, ui ) {

					var ids = ui.newPanel.attr(&#039;id&#039;).split( &#039;_&#039; );
					var tabid = ids[1];
					var type = &#039;virtualmachine&#039;;
					var platform = ids[2];
					var graph_id = "#report_graph_" + tabid + "_" + platform;
					var chart = $( graph_id ).highcharts();
					
					if ( typeof chart !== &#039;undefined&#039; ) {
						return ;
					}
					
					$( graph_id ).highcharts(&#039;StockChart&#039;, options[tabid] );
					if ( tabid == &#039;ip&#039; ) {
						type = &#039;globalip&#039;;
					}
					getData( "/api/report/" + type + "/cloudstack/" + platform, graph_id );
				},
				&#039;create&#039;: function ( event, ui ) {
					var ids = ui.panel.attr(&#039;id&#039;).split( &#039;_&#039; );
					var tabid = ids[1];
					var platform = ids[2];
					var type = &#039;virtualmachine&#039;;
					var graph_id = "#report_graph_" + tabid + "_" + platform;
					var chart = $( graph_id ).highcharts();
					
					if ( typeof chart !== &#039;undefined&#039; ) {
						return ;
					}
					
					$( graph_id ).highcharts(&#039;StockChart&#039;, options[tabid] );
					if ( tabid == &#039;ip&#039; ) {
						type = &#039;globalip&#039;;
					}
					getData( "/api/report/" + type + "/cloudstack/" + platform, graph_id );
				},
			};

		$("#platform").tabs({
			&#039;create&#039;: function ( event, ui ) {
				$("#report_tabs_" + ui.panel.attr(&#039;id&#039;) ).tabs( tabsOptions );
			},
			&#039;activate&#039;: function ( event, ui ) {
				$("#report_tabs_" + ui.newPanel.attr(&#039;id&#039;)).tabs( tabsOptions );
			},
		});

		function setDataTable( id, datalist ) {
			var dataTableID = ( &#039;#&#039; + id ).slice( ( id.length + 1 ) * -1 ).replace( &#039;graph&#039;, &#039;table&#039; );
			var graphID = ( &#039;#&#039; + id ).slice( ( id.length + 1 )* -1 );
			var params = id.split( &#039;_&#039; );
			
			var chartObject = $( graphID ).highcharts();
			var table = $( &#039;<table>&#039; ).attr(&#039;border&#039;, &#039;1&#039;);
			var thead = $( &#039;<thead>&#039; );
			var tbody = $( &#039;<tbody>&#039; );

			var fromDate = chartObject.rangeSelector.minInput.HCTime;
			var toDate = chartObject.rangeSelector.maxInput.HCTime;

			var aryDate = new Array();
			$( dataTableID ).empty();
			
			// ヘッダー領域の作成
			var headTr = $( &#039;<tr>&#039; ).append( $( &#039;<td>&#039; ) );
			
			$.each( datalist, function( key, data ) {
				// データ領域の作成
				var tr = $( &#039;<tr>&#039; ).append( $( &#039;<td>&#039; ).text( data.name ) );
				var oldVmCount = 0;
				
				$.each( data.data, function ( idx, value ) {
					// HighChartの指定日付範囲外は処理しない
					if ( ! ( value[0] >= fromDate && value[0] <= toDate ) ) {
						// 一つ前のデータ取得
						if ( value[0] <= fromDate ) {
							oldVmCount = value[1];
						}
						return true; // continue
					}
					if ( $.inArray( value[0], aryDate ) == -1 ) {
						var dt = new Date( value[0] );
						var dateString = [ dt.getFullYear(), ( &#039;0&#039; + ( dt.getMonth() + 1 ) ).slice( -2 ), ( &#039;0&#039; + dt.getDate() ).slice( -2 ) ].join( &#039;/&#039; ); 
						aryDate.push( value[0] );
						headTr.append( $( &#039;<td>&#039; ).text( dateString ) );
					}

					var vmCount = value[1] - oldVmCount;
					var compareStyle = ( vmCount > 0 ) ? &#039;plus&#039; : ( vmCount < 0 ) ? &#039;minus&#039; : &#039;&#039;;
					var viewVMCount = ( vmCount > 0 ) ? ( &#039;+&#039; + vmCount ).slice( ( vmCount.length + 1 ) * -1 ) : ( vmCount < 0 ) ? vmCount : ( &#039;±&#039; + vmCount ).slice( ( vmCount.length + 1 ) * -1 );
					var bodyTd = $( &#039;<td>&#039; ).text( value[1] ).append( $( &#039;<span>&#039; ).text( &#039; (&#039; + viewVMCount + &#039;)&#039; ).attr( &#039;class&#039;, compareStyle ) );
					oldVmCount = value[1];
					tr.append( bodyTd );
				});
				tbody.append( tr );
			});

			thead.append( headTr );
			table.append( thead );
			table.append( tbody );
			

			$( dataTableID ).append( table );
			
		}

		function exportTableToCSV( $table, filename ) {
			var $rows = $table.find(&#039;tr:has(td)&#039;),
						tmpColDelim = String.fromCharcode(11),
						tmpRowDelim = String.fromCharcode(0),
						colDelim = &#039;","&#039;,
						rowDelim = &#039;"\r\n"&#039;,
						csv = &#039;"&#039; + $rows.map( function( i, row ) {
							var $row = $(row),
								$cols = $row.find( &#039;td&#039; );

							return $cols.map( function( j, col ) {
								var $col = $( col ),
									text = $col.text();

								return text.replace( &#039;"&#039;, &#039;""&#039;);

								}).get().join( tmpColDelim );
						}).get().join( tmpRowDelim )
									.split( tmpRowDelim ).join( rowDelim )
									.split( tmpColDelim ).join( colDelim ) + &#039;"&#039;,
						csvData = &#039;data:application/csv;charset=utf8,&#039; + encodeURIComponent( csv );

			$(this).attr({
				&#039;download&#039;: filename,
				&#039;href&#039;: csvData,
				&#039;target&#039;: &#039;_blank&#039;
				});
		}

		$("a[id^=&#039;export_graph&#039;]").button();
		
		$("a[id^=&#039;export_graph&#039;]").bind( &#039;click&#039;, function( event ) {
			var ids = this.id.split( &#039;_&#039; );
			var tableID = [ &#039;#report&#039;, &#039;table&#039;, ids[2], ids[3] ].join( &#039;_&#039; );
			var chartID = [ &#039;#report&#039;, ids[1], ids[2], ids[3] ].join( &#039;_&#039; );
			var chartObject = $( chartID ).highcharts();
			var fromDate = chartObject.rangeSelector.minInput.HCTime;
			var toDate = chartObject.rangeSelector.maxInput.HCTime;
			var fromDt = new Date( fromDate );
			var toDt = new Date( toDate );
			var fromDateString = [ fromDt.getFullYear(), ( &#039;0&#039; + ( fromDt.getMonth() + 1 ) ).slice( -2 ), ( &#039;0&#039; + fromDt.getDate() ).slice( -2 ) ].join( &#039;&#039; );
			var toDateString = [ toDt.getFullYear(), ( &#039;0&#039; + ( toDt.getMonth() + 1 ) ).slice( -2 ), ( &#039;0&#039; + toDt.getDate() ).slice( -2 ) ].join( &#039;&#039; );
			var exportFileName = [ fromDateString, toDateString, ids[3], ids[2] ].join( &#039;-&#039; ),
				exportFileName = exportFileName + &#039;.csv&#039;;
			
			exportTableToCSV.apply( this, [ $( tableID ), exportFileName ]);
		});

		
		
	});

</script>
14_web/02_gruph_hightcharts.js.txt · 最終更新: 2019/03/25 09:40 by matsui