| | 92 | |
| | 93 | == Jupyter Notebook + HighCharts |
| | 94 | |
| | 95 | Jupyter Notebook + HighChartsでリッチなチャートを表示する例です。 |
| | 96 | |
| | 97 | python-highchartsをpipでインストールしておく必要があります。 |
| | 98 | |
| | 99 | {{{ |
| | 100 | import subprocess |
| | 101 | from subprocess import Popen,PIPE |
| | 102 | from datetime import datetime |
| | 103 | |
| | 104 | from highcharts import Highchart |
| | 105 | H = Highchart(width=640, height=400) |
| | 106 | |
| | 107 | def readSarCPU(f): |
| | 108 | args = ['/bin/bash','-c', "sadf -T -- -C " + f + " |awk '{print $3,$4,$6,$7}'"] |
| | 109 | p = Popen(args,stdout=PIPE,stderr=PIPE) |
| | 110 | out,err = p.communicate() |
| | 111 | cpu = {'%user': [], '%nice': [], '%system': [], '%iowait': [], '%steal': [], '%idle': []} |
| | 112 | timestamp = [] |
| | 113 | x = 0 |
| | 114 | prev = "" |
| | 115 | for l in out.decode('utf8').split('\n'): |
| | 116 | if l == "": |
| | 117 | break; |
| | 118 | r = l.split(" ") |
| | 119 | |
| | 120 | if prev != r[1]: |
| | 121 | timestamp.append(datetime.strptime(r[0]+" "+r[1], '%Y-%m-%d %H:%M:%S')) |
| | 122 | prev = r[1] |
| | 123 | x = x+1 |
| | 124 | cpu[r[2]].append(float(r[3])) |
| | 125 | return (timestamp, cpu) |
| | 126 | |
| | 127 | |
| | 128 | def plot(x, data, highchart, title="",xlabel="",ylabel=""): |
| | 129 | |
| | 130 | options = { |
| | 131 | 'title': { |
| | 132 | 'text': 'CPU Usage' |
| | 133 | }, |
| | 134 | 'subtitle': { |
| | 135 | 'text': 'Source: test.sar' |
| | 136 | }, |
| | 137 | 'xAxis': { |
| | 138 | 'type': 'datetime', |
| | 139 | 'minRange': 1000*len(x) |
| | 140 | }, |
| | 141 | 'yAxis': { |
| | 142 | 'title': { |
| | 143 | 'text': ylabel |
| | 144 | }, |
| | 145 | 'labels': { |
| | 146 | 'formatter': 'function () {\ |
| | 147 | return this.value ;\ |
| | 148 | }' |
| | 149 | }, |
| | 150 | 'max': 100 |
| | 151 | }, |
| | 152 | 'tooltip': { |
| | 153 | 'shared': True, |
| | 154 | 'valueSuffix': ylabel |
| | 155 | }, |
| | 156 | 'plotOptions': { |
| | 157 | 'area': { |
| | 158 | 'stacking': 'normal', |
| | 159 | 'lineColor': '#666666', |
| | 160 | 'lineWidth': 1, |
| | 161 | 'marker': { |
| | 162 | 'lineWidth': 1, |
| | 163 | 'lineColor': '#666666' |
| | 164 | } |
| | 165 | } |
| | 166 | } |
| | 167 | } |
| | 168 | highchart.set_dict_options(options) |
| | 169 | for k in data.keys(): |
| | 170 | highchart.add_data_set(data[k],'area',k,pointInterval=1000, pointStart=x[0]) |
| | 171 | |
| | 172 | timestamp, cpu = readSarCPU("test.sar") |
| | 173 | plot(x=timestamp, data=cpu,ylabel=u"%",xlabel=u"time",highchart=H) |
| | 174 | H |
| | 175 | }}} |