首页 > 数据库技术 > 详细

Python利用Plotly实现对MySQL中的数据可视化

时间:2018-05-06 15:49:28      阅读:390      评论:0      收藏:0      [点我收藏+]

Mysql表数据:

技术分享图片

demo.sql内容

create table demo(
 id int
,product varchar(50)
,price decimal(18,2)
,quantity int
,amount decimal(18,2)
,orderdate datetime
);
insert into demo
select 1,AAA,15.2,5,76,2017-09-09 union all
select 2,BBB,10,6,60,2016-05-18 union all
select 3,CCC,21,11,231,2014-07-11 union all
select 4,DDD,55,2,110,2016-12-24 union all
select 5,EEE,20,4,80,2017-02-08 union all
select 6,FFF,45,2,90,2016-08-19 union all
select 7,GGG,33,5,165,2017-10-11 union all
select 8,HHH,5,40,200,2014-08-30 union all
select 9,III,3,20,60,2015-02-25 union all
select 10,JJJ,10,15,150,2015-11-02;

 

实现效果如下:

技术分享图片

 

Python代码:

 1 import pymysql
 2 import pandas as pd
 3 import plotly.plotly
 4 import plotly.graph_objs as pg
 5 
 6 
 7 def bar_chart(host, port, user, passwd, dbname, charset,output_path):
 8     try:
 9         conn = pymysql.Connection(
10             host=host,
11             port=port,
12             user=user,
13             passwd=passwd,
14             db=dbname,
15             charset=charset
16         )
17         cur = conn.cursor()
18         cur.execute("select * from demo;")
19         # cursor对象使用MySQL查询字符串执行查询,返回一个包含多个元组的元组——每行对应一个元组
20         rows = cur.fetchall()
21         # print(rows)
22 
23         # 使用Pandas的DataFrame来处理每一行要比使用一个包含元组的元组方便
24         # 下面的Python代码片段将所有行转化为DataFrame实例
25         df = pd.DataFrame([[ij for ij in i] for i in rows])
26         print(df)
27         df.rename(columns={0: id, 1: product, 2: price, 3: quantity, 4: amount, 5: orderdate}, inplace=True)
28         # df = df.sort([‘LifeExpectancy‘], ascending=[1])
29 
30         date_price = pg.Bar(x=df["product"], y=df["price"], name=价格)
31         date_quantity = pg.Bar(x=df["product"], y=df["quantity"], name=数量)
32         date_amount = pg.Bar(x=df["product"], y=df["amount"], name=总价)
33         data = [date_price, date_quantity, date_amount]
34 
35         layout = pg.Layout(barmode=group, title="各产品销售情况")
36         fig = pg.Figure(data=data, layout=layout)
37         plotly.offline.plot(fig, filename=output_path)
38 
39     finally:
40         if conn:
41             conn.close()
42 
43 
44 if __name__ == __main__:
45     output_path = "C:/Users/fuqia/Desktop/bar.html"
46     bar_chart("localhost", 3306, "root", "123456", "test", "utf8", output_path)

 

 输出df内容如下:
技术分享图片

Python利用Plotly实现对MySQL中的数据可视化

原文:https://www.cnblogs.com/fuqia/p/8998290.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!