【python】使用plotly生成图表数据
安装
在 ubuntu 环境下,安装 plotly 很简单
python 版本2.7+
pip install plotly
绘图
在 plotly 网站注册后,可以直接将生成的图片保存到网站上,便于共享保存。
这里使用离线的接口,生成的 html 保存在本地文件
绘制直线图
先随便搞一组数据用来绘制图表
1 lcd@ubuntu:~/$ cat gen_log.sh 2 #!/bin/bash 3 count=$1 4 while [ $count -gt 0 ] 5 do 6 sar -n DEV 1 1 | grep "Average:" | grep "eth0" | awk '{print $4,$5,$6}' 7 count=$(($count-1)) 8 done 9 lcd@ubuntu:~/$ sh gen_log.sh 1000 > log.txt
通过上述脚本,获取每秒钟网卡的3个数据,记录文本,利用 ploty 按时间绘制成直线图,实现如下:
1 #!/usr/bin/env python 2 import plotly.offline as pltoff 3 import plotly.graph_objs as go 4 5 def line_plots(name="line_plots.html"): 6 dataset = { 7 'time': [], 8 'rx': [], 9 'tx': [], 10 'util': [] 11 } 12 with open("./log.txt") as f: 13 i = 0 14 for line in f: 15 items = line.split() 16 dataset['time'].append(i) 17 dataset['rx'].append(items[0]) 18 dataset['tx'].append(items[1]) 19 dataset['util'].append(items[2]) 20 i += 1 21 22 data_g = [] 23 # 构建 time - rx 数据关系,折线图 24 tr_rx = go.Scatter( 25 x = dataset['time'], 26 y = dataset['rx'], 27 name = 'rx') 28 data_g.append(tr_rx) 29 30 tr_tx = go.Scatter( 31 x = dataset['time'], 32 y = dataset['tx'], 33 name = 'tx') 34 data_g.append(tr_tx) 35 36 tr_util = go.Scatter( 37 x = dataset['time'], 38 y = dataset['util'], 39 name = 'util') 40 data_g.append(tr_util) 41 42 # 设置图表布局 43 layout = go.Layout(title="Line plots", 44 xaxis={'title':'time'}, yaxis={'title':'value'}) 45 fig = go.Figure(data=data_g, layout=layout) 46 # 生成离线html 47 pltoff.plot(fig, filename=name) 48 49 if __name__=='__main__': 50 line_plots()
生成图表如下所示 :
柱形图
1 #!/usr/bin/env python 2 import plotly.offline as pltoff 3 import plotly.graph_objs as go 4 5 def bar_charts(name="bar_charts.html"): 6 dataset = {'x':['man', 'woman'], 7 'y1':[35, 26], 8 'y2':[33, 30]} 9 data_g = [] 10 tr_y1 = go.Bar( 11 x = dataset['x'], 12 y = dataset['y1'], 13 name = '2016' 14 15 ) 16 data_g.append(tr_y1) 17 18 tr_y2 = go.Bar( 19 x = dataset['x'], 20 y = dataset['y2'], 21 name = '2017' 22 23 ) 24 data_g.append(tr_y2) 25 layout = go.Layout(title="bar charts", 26 xaxis={'title':'x'}, yaxis={'title':'value'}) 27 fig = go.Figure(data=data_g, layout=layout) 28 pltoff.plot(fig, filename=name) 29 30 if __name__=='__main__': 31 bar_charts()
饼状图
1 #!/usr/bin/env python 2 import plotly.offline as pltoff 3 import plotly.graph_objs as go 4 5 def pie_charts(name='pie_chart.html'): 6 dataset = { 7 'labels':['Windows', 'Linux', 'MacOS'], 8 'values':[280, 10, 30]} 9 data_g = [] 10 tr_p = go.Pie( 11 labels = dataset['labels'], 12 values = dataset['values'] 13 14 ) 15 data_g.append(tr_p) 16 layout = go.Layout(title="pie charts") 17 fig = go.Figure(data=data_g, layout=layout) 18 pltoff.plot(fig, filename=name) 19 20 if __name__=='__main__': 21 pie_charts()
原文链接:http://www.jianshu.com/p/c2997494085b