生活会辜负努力的人,但不会辜负一直努力的人

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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内容如下:

posted on 2018-05-06 15:00  何许亻也  阅读(3939)  评论(0编辑  收藏  举报