Python动态绘图的方法(matplotlib,matplotlib.animation,pyechart,echart)
目录
方法二:matplotlib循环刷新-清除旧数据-添加新数据 1
方法三、利用第三方插件imagemagick实现动态图保存gif文件 2
方法四:利用pyecharts实现图展示-保存为html 3
方法五:利用flask和pyechart组合-web发布图形 4
方法六:利用flask发布静态echart的html网页 7
方法七:利用flask+ajax+echart+json发布异步图形网页 8
方法八:flask+ajax+echart+json+mysql的自动刷新网页展示数据库数据 11
方法一:matplotlib循环添加数据
import numpy as np
import matplotlib.pyplot as plt
"""
动态绘图方法一:
通过刷新图面的方法,每次循环在绘制新图画前,把当前绘图区的内容进行清空,
然后绘制新的图形
"""
fig=plt.figure() #设置图面大小
plt1=plt.subplot(211) #设置绘图区域2行1列,第一个图区
plt2=plt.subplot(212)#设置绘图区域2行1列,第二个图区
plt1.axis([0, 100, 0, 1])
xa=[]
ya = []
pause_time=0.01 #动态刷新时间
for i in range(50):
y = np.random.random()
ya.append(y) # 每迭代一次,将i放入y1中画出来
xa.append(i)
plt1.cla() # 清除键
plt1.plot(xa,ya)
plt.pause(pause_time)
方法二:matplotlib循环刷新-清除旧数据-添加新数据
"""
利用绘图的特性,每次绘制的内容,在前一次的结果上添加,
这个方法需要对数据进行特殊处理,每次绘制的数据,只有新添加的数据,旧的数据需要删除
"""
plt2.axis([0, 100, 0, 1])
xs = [0, 0]
ys = [1, 1]
for i in range(50):
y = np.random.random()
xs[0] = xs[1]
ys[0] = ys[1]
xs[1] = i
ys[1] = y
plt2.plot(xs, ys)
plt.pause(pause_time)
plt.show()
方法三、利用第三方插件imagemagick实现动态图保存gif文件
- 首先现在imagemagick软件,这里有个坑,需要下载6.9版本的,应为7.0版本没有了convert.exe命令,必须用6.9版本的,网上的教程都是用的这个convert命令
- 安装完,imagemagick后,matplotlib并不知道这个命令所在的位置,因此需要告诉命令convert的绝对位置
在python中利用print(matplotlib.matplotlib_fname()),获得matplotlib配置文件的位置,在最后一行,修改命令的全局路径
,为animation.convert_path: D:\Program Files\ImageMagick-6.9.10-Q16\convert.exe
- 在程序中就可以正常使用了
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation
print(matplotlib.matplotlib_fname()) # 修改matplotlib配置文件的位置
fig = plt.figure() # 画纸
ax = plt.subplot() # 绘图区
xdata, ydata = [], [] # x,y轴数据数组
ln, = plt.plot([], [], 'r', animated=True) #
def init():
ax.set_xlim(0, 100)
ax.set_ylim(0, 1)
return ln,
def update(frame): #frame的数据来自FuncAnimation函数frams的内容,每次调用函数,区frames中的一个数据
xdata.append(frame)
# print(frame)
ydata.append(np.random.random())
ln.set_data(xdata, ydata) #在ln中添加数据
return ln,
anim = animation.FuncAnimation(fig, update, frames=range(10,60), interval=10, init_func=init, blit=True, repeat=False)
# anim.save('sinx.gif', writer='imagemagick') #存储为gif文件
# anim.save('sinx2.html') #利用默认的工具,存储为html文件
plt.show()
- 利用echart进行实现,利用网页形式,在web前端显示图形,让后利用echart获得后台的数据
- 需要工具,echart,flask
- pip install echarts
- 保存为gif
- 1.如果想直接将图片保存为 png, pdf, gif 格式的文件,可以使用 pyecharts-snapshot。使用该插件请确保你的系统上已经安装了 Nodejs 环境。
- 安装 phantomjs $ npm install -g phantomjs-prebuilt
- 安装 pyecharts-snapshot $ pip install pyecharts-snapshot
- 调用 render 方法 bar.render(path='snapshot.png') 文件结尾可以为 svg/jpeg/png/pdf/gif。请注意,svg 文件需要你在初始化 bar 的时候设置 renderer='svg'。
首先利用pyecharts画一个静态的图形
#http://pyecharts.org/#/zh-cn/prepare 帮助文件
from pyecharts import Line
import numpy as np
x=list(range(0,50))
y1=list(np.random.random(50))
y2=list(np.random.random(50))
y2=[m/2 for m in y2 if m>0] #for的迭代式式,加过滤器if,生产list
line=Line("折线图")
line.add("A",x,y1,mark_point=["average"],line_width=3,line_color="red")
line.add("B",x,y2,mark_point=["average"],line_width=3,line_color="blue")
#line.show_config()
line.render("myechart001.html") #生成html文件
import webbrowser
webbrowser.open("myechart001.html") #
方法五:利用flask和pyechart组合-web发布图形
- 首先要安装flask框架
- 在windows的命令行执行:python -m venv myenv
- 进入虚拟环境命令的脚本文件夹,激活虚拟环境
- 然后安装flask包
- 建立html模板目录结构
两个文件的代码如下
python程序如下
import random
from pyecharts import Scatter3D
from flask import Flask, render_template
app = Flask(__name__)
REMOTE_HOST = "https://pyecharts.github.io/assets/js"
@app.route("/")
def hello():
s3d = scatter3d()
return render_template(
"pyecharts.html",
myechart=s3d.render_embed(),
host=REMOTE_HOST,
script_list=s3d.get_js_dependencies(),
)
def scatter3d():
data = [generate_3d_random_point() for _ in range(80)]
range_color = [
"#313695",
"#4575b4",
"#74add1",
"#abd9e9",
"#e0f3f8",
"#fee090",
"#fdae61",
"#f46d43",
"#d73027",
"#a50026",
]
scatter3D = Scatter3D("3D scattering plot demo", width=1200, height=600)
scatter3D.add("", data, is_visualmap=True, visual_range_color=range_color)
return scatter3D
def generate_3d_random_point():
return [
random.randint(0, 100), random.randint(0, 100), random.randint(0, 100)
]
if __name__=='__main__':
app.run(debug=True)
html文件的内容如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Proudly presented by ECharts</title>
{% for jsfile_name in script_list %}
<script src="{{ host }}/{{ jsfile_name }}.js"></script>
{% endfor %}
</head>
<body>
{{ myechart|safe }}
</body>
</html>
- 在pycharm中运行server.py文件,在浏览器中访问127.0.0.1:5000即可
这是官方的例子。
在此基础上修改为折线图
from pyecharts import Line #引入不同的图形模块
from flask import Flask, render_template
import numpy as np
app = Flask(__name__)
REMOTE_HOST = "https://pyecharts.github.io/assets/js" #远程js库,可以下载全部到自己的服务器上,修改这个路径就可以了
@app.route("/")
def hello():
myline=mydata_line() #这个地方就是基本的pyechart图形绘制,返回一个图形对象
return render_template(
"pyecharts.html", #模板的名称,模板默认位置在templates文件夹下
myechart=myline.render_embed(), #给模板传递echart图形参数
host=REMOTE_HOST, #js库的位置
script_list=myline.get_js_dependencies(), #给模块传echart图形的js代码,我理解的,不一定对
)
#此函数就是普通的画图函数,数据怎么处理都可以,利用基本知识
def mydata_line():
x=list(range(50))
y1=list(np.random.random(50))
y2=list(np.random.random(50))
line=Line("折线图flask")
line.add("A",x,y1)
line.add("B",x,y2)
#line.render("myechart001.html") # 生成html文件,这是静态方法生成网页
return line
if __name__=='__main__':
app.run(debug=True)
html文件的内容不变,还利用官方例子的内容。
这种方法,比较简单可以快速的发布html格式的网页,但是问题是html网页的内容比较单一,需要根据需求进行修改,但是应用的案例比较少,属于小众方法。
主要问题:没有方法实现动态刷新图形图形的方法,图形都是利用已知的数据,生成静态的html网页进行发布,因此不适用动态刷新的方法
扩展思路,直接利用底层得echart进行数据展示
思路:利用flask发布静态网页,但是html网页是echart的网页,需要js渲染,因此需要jinjia2库支持,渲染网页。这里需要主要flask的默认文件夹结构,pro/static,pro/templates,pro/,分别方法JS/CSS/IMAGE,html,py程序
#python文件内容
from flask import Blueprint,render_template,send_file
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return render_template('pyecharts2_1.html') #调用模板
if __name__=='__main__':
app.run(debug=True)
html文件内容,修改了官方的例子,把js文件的位置,写为了绝对路径,不要跟html文件在一个目录里面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ECharts</title>
<!-- 引入 echarts.js -->
<script src="/static/echarts.min.js"></script>
</head>
<body>
<font face="黑体" color="red">文字的字体和颜色</font>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 600px;height:400px;"></div>
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 指定图表的配置项和数据
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data:['销量']
},
xAxis: {
data: ["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"]
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}]
};
// 使用刚指定的配置项和数据显示图表。
myChart.setOption(option);
</script>
</body>
</html>
方法七:利用flask+ajax+echart+json发布异步图形网页
思路:静态方法,echart的html网页的数据是写死的,因此需要修改网页的数据内容,利用echart的js库提供的接口功能,经过搜索,考虑使用ajax+Jason的方法。用户首先访问网页/,获得模板html,但是模板里面只有js的脚本,没有数据,因此再次利用ajax访问/test,获得json数据,然后把json数据利用js进行解析,添加到html网页中进行显示。如果需要动态刷新,在html中添加js的定时器函数,利用间隔时间发送ajax请求数据,刷新页面
参考:轮询和长轮询https://blog.csdn.net/submarineas/article/details/84176840
#python程序
from flask import Flask,render_template,url_for
import json
import numpy as np
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('my_template.html')
# /test路由 接收前端的ajax请求
@app.route('/test',methods=['POST'])
def my_echart():
xdays = list(range(0, 50))
yvalues1 = list(np.random.random(50))
yvalues2= list(np.random.random(50))
# 转换成JSON数据格式
jsonData = {} #准备存储json数据的字典
jsonData['xdays']=xdays
jsonData['yvalues1'] = yvalues1
jsonData['yvalues2'] = yvalues2
# json.dumps()用于将dict类型的数据转成str,因为如果直接将dict类型的数据写入json会发生报错,因此将数据写入时需要用到该函数。
j = json.dumps(jsonData)
# 在浏览器上渲染my_template.html模板(为了查看输出的数据)
return(j)
if __name__ == '__main__':
app.run(debug=True)
#html模板
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>炫酷的ECharts</title>
<script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/echarts/4.1.0.rc2/echarts.min.js"></script>
</head>
<body>
<font face="黑体" color="red">my_template</font>
<!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 800px;height:500px;margin: 0 auto;"></div>
<script type="text/javascript">
var myChart = echarts.init(document.getElementById('main'));
var app = {
xday:[],
yvalue1:[],
yvalue2:[]
};
// 发送ajax请求,从后台获取json数据
$(document).ready(function () {
getData();
console.log(app.xday);
console.log(app.yvalue1);
console.log(app.yvalue2)
});
function getData() {
$.ajax({
url:'/test',
data:{},
type:'POST',
async:false,
dataType:'json',
success:function(data) {
app.xday = data.xdays;
app.yvalue1 = data.yvalues1;
app.yvalue2 = data.yvalues2;
myChart.setOption({
title: {
text: '异步数据加载示例'
},
tooltip: {},
legend: {
data:['销量1','销量2']
},
xAxis: {
data: app.xday
},
yAxis: {},
series: [{
name: '销量1',
type: 'line', //echart的图形类型'bar'
data: app.yvalue1
},
{
name: '销量2',
type: 'line', //echart的图形类型'bar'
data: app.yvalue2
}
]
})
},
error:function (msg) {
console.log(msg);
alert('系统发生错误');
}
})
};
setInterval(getData,3000); //很关键的,自动轮寻,3秒一次,动态刷新
</script>
</body>
</html>
方法八:flask+ajax+echart+json+mysql的自动刷新网页展示数据库数据
参考:轮询和长轮询https://blog.csdn.net/submarineas/article/details/84176840
Sql参考https://blog.csdn.net/u014465934/article/details/80556340
- 先连接mysql数据库
- 从数据库读取数据,元祖形式。然后填充到图形中
- 其它内容,跟前面一样,利用定时器html动态刷新界面,获得后台最新的mysql的数据。
#python程序
#coding:utf-8
from flask import Flask,render_template,url_for
import pymysql
import json
# 生成Flask实例
app = Flask(__name__)
@app.route('/')
def hello():
return render_template('my_template.html')
# /test路由 接收前端的ajax请求
@app.route('/test',methods=['POST'])
def my_echart():
# 连接数据库
conn = pymysql.connect(host='127.0.0.1',user='root',password='123456',db='mydb001')
cur = conn.cursor()
sql = 'SELECT * FROM tb1'
cur.execute(sql)
u = cur.fetchall()
# 转换成JSON数据格式
jsonData = {}
xdays = []
yvalues1 = []
yvalues2 = []
for data in u:
# xdays.append(str(data[0]))
xdays.append(data[0])
yvalues1.append(data[1])
yvalues2.append(data[2])
print(xdays,yvalues1,yvalues2)
jsonData['xdays']=xdays
jsonData['yvalues1'] = yvalues1
jsonData['yvalues2'] = yvalues2
# json.dumps()用于将dict类型的数据转成str,因为如果直接将dict类型的数据写入json会发生报错,因此将数据写入时需要用到该函数。
j = json.dumps(jsonData)
cur.close()
conn.close()
# 在浏览器上渲染my_template.html模板(为了查看输出的数据)
return(j)
if __name__ == '__main__':
# 运行项目
app.run(debug=True)
Html程序跟前面程序一样,不变
程序下载:链接:https://pan.baidu.com/s/1xeLlOHtDKhgBf5qQCJoh0Q
提取码:wvam