一、环境准备

1.准备Flask开发环境

安装包

  1. flask
  2. flask-sqlalchemy
  3. flask-mysqldb

创建flask实例

  1. app = Flask(__name__)

创建蓝图

  1. # -*- coding:utf-8 -*-
  2. # Created by ZhaoWen on 2020/10/11
  3. from flask import Blueprint
  4. matplot_print = Blueprint('matplot_print',__name__)
  5. @matplot_print.route('/mat')
  6. def index():
  7. return 'Hello Matplotlib !'

注册蓝图

  1. app.register_blueprint(matplot_print,prefix='')

此时我们在控制台查看url映射,就可以看到matplot_print视图已经成功注册到flask主程序中去了

  1. <Rule '/mat' (OPTIONS, HEAD, GET) -> matplot_print.index>,

此时启动flask应用,访问指定路径已经可以成功访问了

2.准备matplotlib开发环境

  1. pipenv install matplotlib

安装时间比较长,耐心等候

二、数据准备

我们直接使用数据库中的数据

1.ORM映射实体类

  1. class Tbl_Video_Game_Sales(db.Model):
  2. __tablename__ = 't_video_game_sales'
  3. Rank = db.Column(db.String(255),primary_key=True) #销售排名
  4. Name = db.Column(db.String(255)) #游戏名称
  5. Platform = db.Column(db.String(255)) #该游戏发布平台
  6. Year = db.Column(db.Integer) #发布年份(1980-2016)
  7. Genre = db.Column(db.String(255)) #游戏类型
  8. Publisher = db.Column(db.String(255)) #出版公司
  9. NA_Sales = db.Column(db.DECIMAL(255,2)) #北美区域销量(以百万为单位计数)
  10. EU_Sales = db.Column(db.DECIMAL(255,2)) #欧美区域销量(以百位为单位计数)
  11. JP_Sales = db.Column(db.DECIMAL(255,2)) #日本区域销量(以百位为单位计数)
  12. Other_Sales = db.Column(db.DECIMAL(255,2)) #其他国家销量(以百位为单位计数)
  13. Global_Sales = db.Column(db.DECIMAL(255,2)) #全球销量(以百位为单位计数)

2.进行简单查询

  1. Tbl_Video_Game_Sales.query.all()[:10]

执行上面那条语句,我们从数据库中获得了十个对象

  1. <Tbl_Video_Game_Sales 1>
  2. <Tbl_Video_Game_Sales 2>
  3. <Tbl_Video_Game_Sales 3>
  4. <Tbl_Video_Game_Sales 4>
  5. <Tbl_Video_Game_Sales 5>
  6. <Tbl_Video_Game_Sales 6>
  7. <Tbl_Video_Game_Sales 7>
  8. <Tbl_Video_Game_Sales 8>
  9. <Tbl_Video_Game_Sales 9>
  10. <Tbl_Video_Game_Sales 10>

执行一个简单的循环遍历,获取到每个对象的名字

  1. Wii Sports
  2. Super Mario Bros.
  3. Mario Kart Wii
  4. Wii Sports Resort
  5. Pokemon Red/Pokemon Blue
  6. Tetris
  7. New Super Mario Bros.
  8. Wii Play
  9. New Super Mario Bros. Wii
  10. Duck Hunt

三、图形实战

2000~2010(不含)之间全球游戏销量最高的前十位

  1. Tbl_Video_Game_Sales.query.filter(Tbl_Video_Game_Sales.Year>2000).filter(Tbl_Video_Game_Sales.Year<2005).order_by(Tbl_Video_Game_Sales.Global_Sales.desc())[:10]

1.柱状图(bar)

2000~2010(不含)之间全球游戏销量最高的前十位

  1. Tbl_Video_Game_Sales.query.filter(Tbl_Video_Game_Sales.Year>2000).filter(Tbl_Video_Game_Sales.Year<2005).order_by(Tbl_Video_Game_Sales.Global_Sales.desc())[:10]
  1. @matplot_print.route('/mat/bar-show')
  2. def bar_show():
  3. data = Tbl_Video_Game_Sales.query.filter(Tbl_Video_Game_Sales.Year>2000).filter(Tbl_Video_Game_Sales.Year<2005).order_by(Tbl_Video_Game_Sales.Global_Sales.desc())[:10]
  4. path = 'mat_bar.jpg'
  5. if os.path.exists(root+path) is False:
  6. get_bar(data,path)
  7. return render_template('/matplotlib/bar-chart.html',path=path)
  8. def get_bar(data,path):
  9. '''
  10. 柱状图
  11. :param data:
  12. :return:
  13. '''
  14. bar_x = list()
  15. bar_y = list()
  16. for d in data:
  17. bar_x.append(d.Name)
  18. bar_y.append(d.Global_Sales)
  19. for x,y in zip(bar_x,bar_y):
  20. plt.text(x+3, y + 1, '%.2f' % y, ha='center', va='bottom')
  21. plt.bar(bar_x,bar_y) # 直角坐标轴 设置颜色
  22. plt.savefig('.'+root+path)

最终效果
Matplotlib | Matplotlib在Flask开发环境下的数据可视化绘图实战 - 图1这里因为数据格式问题,x轴的字体挤在一起了,之后进行调整

2.折线图

  1. def get_line(data,path):
  2. '''
  3. 折线图
  4. :param data:
  5. :param path:
  6. :return:
  7. '''
  8. x = [d.Name for d in data] # 横坐标轴
  9. y = [float(d.Global_Sales) for d in data] # 纵坐标轴
  10. plt.plot(x,y)
  11. plt.savefig('.'+root+path)

3.饼图

  1. def get_pie(data,path):
  2. '''
  3. 饼图
  4. :param data:
  5. :param path:
  6. :return:
  7. '''
  8. sizes = [d.Global_Sales for d in data]
  9. labels = [d.Name for d in data]
  10. plt.pie(x=sizes,shadow=True,labels=labels)
  11. plt.title('2000年~2010年游戏全球销量前十')
  12. # plt.legend(labels) # 图例
  13. plt.savefig('.'+root+path)

效果
Matplotlib | Matplotlib在Flask开发环境下的数据可视化绘图实战 - 图2

四、参考资料/扩展阅读

《Python数据可视化编程实战》:https://book.douban.com/subject/26378430/

《matplotlib官方文档》:https://matplotlib.org/users/index.html

Matplotlib教程-莫烦Python:https://www.bilibili.com/video/BV1Jx411L7LU?p=2

数据化雷达图教程:https://www.bilibili.com/video/BV1PQ4y1M7x7?t=4688

五、常见问题

1.图片中文字体乱码或者非正常显示

  1. plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']

2.TypeError: ‘list’ object cannot be interpreted as an integer

  1. 出现位置:调用numpy.concatenate()方法时报错
  2. 问题出现原因:传入参数没有按照concatenate((a1, a2, ...), axis=0, out=None)的格式来,比如我报错的原因就是把theta = np.concatenate((theta, [theta[0]]))错写为theta = np.concatenate(theta, [theta[0]])