ユーザ用ツール

サイト用ツール


サイドバー

このページの翻訳:



最近の更新



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: 'spline', // 柔らかいLine
    65	                backgroundColor: '#ffffff',
    66	                plotBackgroundColor: '#eeeeee',
    67	                borderRadius: 10,
    68	                borderWidth: 1,
    69	                borderColor: '#dddddd',
    70	            },
    71	            legend: {
    72	                enabled: true,
    73	                align: 'right',
    74	                layout: 'vertical',
    75	                verticalAlign: 'top',
    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: 'ドメインごとのVM数の推移' },
    99	            xAxis: {
   100	                type: 'datetime',
   101	            },
   102	            subtitle: { 
   103	                text: '' 
   104	            }, 
   105	            yAxis: { 
   106	                allowDecimals: false,
   107	                title: { 
   108	                    text: '仮想サーバ数' 
   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: '%Y-%m-%d'
   126	                }
   127	            },
   128	        };
   129	
   130	        function getData(url, graph_id ) { // ajaxでデータ取得
   131	            $.ajax({
   132	                url: url,
   133	                type: 'GET',
   134	                dataType: 'json',
   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	        $('#domain .domainname').click(function(){
   156	                var graph_id = '#domain_graph';
   157	                var id = $(this).attr('id');
   158	                console.log(id);
   159	                options.subtitle.text = id;
   160	                $( graph_id ).highcharts('StockChart', options);
   161	                $("body,html").animate({scrollTop:0},800); // topまでゆっくり上がる
   162	                getData('/api/cloudstack_domains/domain/' + 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 = { 'isolate': { 'vm': {}, 'ip': {} }, 'basic': { 'vm': {}, 'ip': {} } };
		var dataLength = { 'isolate': { 'vm': 1, 'ip': 1 }, 'basic': { 'vm': 1, 'ip': 1 } };
		
		// VM
		var options = { 
			'vm': {
				chart: {
					type: 'line',
					events: {
						redraw: function() {
							var params = this.renderTo.id.split( '_' );
							if ( this.series.length == ( dataLength[ params[3] ][ params[2] ] + 1 ) ) {
	 							setDataTable( this.renderTo.id, jsonData[ params[3] ][ params[2] ] );
							}
						},
					},
				},
				legend: {
					enabled: true,
					layout: 'horizontal',
				},
				title: { text: '各ホスト(HV)ごとのVM数の推移' },
				xAxis: { 
					allowDecimals: false,
					type: 'datetime',
					dateTimeLabelFormats: {
						day: '%m/%d',
						month: '%Y/%m',
					},
					labels: {
	//					format: '{value:%Y/%m/%d}',
	//					rotation: 45,
	//					align: 'left',
						},
	//				startOnTick: true,
					},
				yAxis: { 
					allowDecimals: false,
					title: { 
						text: '仮想サーバ数' 
						}, 
					startOnTick: false,
					min: 0,
					},
				rangeSelector: {
					selected: 0,
				},
				navigator: {
					series: {
						includeInCSVExport: false
					},
				},
				exporting: {
					csv: {
						dateFormat: '%Y-%m-%d'
					}
				},
			},
			'ip': {
				chart: {
					type: 'area',
					events: {
						redraw: function() {
							var params = this.renderTo.id.split( '_' );
							if ( this.series.length == ( dataLength[ params[3] ][ params[2] ] + 1 ) ) {
	 							setDataTable( this.renderTo.id, jsonData[ params[3] ][ params[2] ] );
							}
						},
					},
				},
				legend: {
					enabled: true,
					layout: 'horizontal',
				},
				pilotOptions: {
					series: {
						stacking: 'normal',
					},
				},
				tooltip: {
					formatter: function() {
						var date = Highcharts.dateFormat("%Y/%m/%d", this.x);
						var s = '<b>' + date +'</b>';
						var total = this.points[0].y;
						
						$.each(this.points, function ( i, point ) {
							var percent = Highcharts.numberFormat((point.y / total) * 100, 2);
							var strPercent = '(' + percent + '%)'
							s += '<br />' + point.series.name + ' : <b>' + point.y + '</b>';
							if ( i != 0 ) {
								s+= strPercent;
							}
						});
							
						return s;
					},
					shared: true
				},
				title: { text: 'グローバルIPの利用推移' },
				xAxis: { 
					allowDecimals: false,
					type: 'datetime',
					dateTimeLabelFormats: {
						day: '%m/%d',
						month: '%Y/%m',
					},
					labels: {
	//					format: '{value:%Y/%m/%d}',
	//					rotation: 45,
	//					align: 'left',
					},
	//				startOnTick: true,
				},
				yAxis: { 
					allowDecimals: false,
					title: { 
						text: 'グローバルIP数' 
					}, 
				},
				rangeSelector: {
					selected: 0,
				},
			},
		};

		function getData(url, graph_id ) {
			$.ajax({
				url: url,
				type: 'GET',
				dataType: 'json',
				data: {},
				async: true,
				cache: false,
				success: function (data) {
					var chart = $( graph_id ).highcharts();
					var params = graph_id.split( '_' );
					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 = {
				'activate': function ( event, ui ) {

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

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

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

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

			var aryDate = new Array();
			$( dataTableID ).empty();
			
			// ヘッダー領域の作成
			var headTr = $( '<tr>' ).append( $( '<td>' ) );
			
			$.each( datalist, function( key, data ) {
				// データ領域の作成
				var tr = $( '<tr>' ).append( $( '<td>' ).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(), ( '0' + ( dt.getMonth() + 1 ) ).slice( -2 ), ( '0' + dt.getDate() ).slice( -2 ) ].join( '/' ); 
						aryDate.push( value[0] );
						headTr.append( $( '<td>' ).text( dateString ) );
					}

					var vmCount = value[1] - oldVmCount;
					var compareStyle = ( vmCount > 0 ) ? 'plus' : ( vmCount < 0 ) ? 'minus' : '';
					var viewVMCount = ( vmCount > 0 ) ? ( '+' + vmCount ).slice( ( vmCount.length + 1 ) * -1 ) : ( vmCount < 0 ) ? vmCount : ( '±' + vmCount ).slice( ( vmCount.length + 1 ) * -1 );
					var bodyTd = $( '<td>' ).text( value[1] ).append( $( '<span>' ).text( ' (' + viewVMCount + ')' ).attr( 'class', 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('tr:has(td)'),
						tmpColDelim = String.fromCharcode(11),
						tmpRowDelim = String.fromCharcode(0),
						colDelim = '","',
						rowDelim = '"\r\n"',
						csv = '"' + $rows.map( function( i, row ) {
							var $row = $(row),
								$cols = $row.find( 'td' );

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

								return text.replace( '"', '""');

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

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

		$("a[id^='export_graph']").button();
		
		$("a[id^='export_graph']").bind( 'click', function( event ) {
			var ids = this.id.split( '_' );
			var tableID = [ '#report', 'table', ids[2], ids[3] ].join( '_' );
			var chartID = [ '#report', ids[1], ids[2], ids[3] ].join( '_' );
			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(), ( '0' + ( fromDt.getMonth() + 1 ) ).slice( -2 ), ( '0' + fromDt.getDate() ).slice( -2 ) ].join( '' );
			var toDateString = [ toDt.getFullYear(), ( '0' + ( toDt.getMonth() + 1 ) ).slice( -2 ), ( '0' + toDt.getDate() ).slice( -2 ) ].join( '' );
			var exportFileName = [ fromDateString, toDateString, ids[3], ids[2] ].join( '-' ),
				exportFileName = exportFileName + '.csv';
			
			exportTableToCSV.apply( this, [ $( tableID ), exportFileName ]);
		});

		
		
	});

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