Python uses Plotly to visualize data in MySQL

Mysql table data:

Realize the effect:

Python code:

 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         rows = cur.fetchall()
20         # print(rows)
21         df = pd.DataFrame([[ij for ij in i] for i in rows])
22         print(df)
23         df.rename(columns={0: 'id', 1: 'product', 2: 'price', 3: 'quantity', 4: 'amount', 5: 'orderdate'}, inplace=True)
24         # df = df.sort(['LifeExpectancy'], ascending=[1])
25 
26         date_price = pg.Bar(x=df["product"], y=df["price"], name='价格')
27         date_quantity = pg.Bar(x=df["product"], y=df["quantity"],name='数量')
28         date_amount = pg.Bar(x=df["product"], y=df["amount"], name='总价')
29         data = [date_price, date_quantity, date_amount]
30 
31         layout = pg.Layout(barmode='group', title="各产品销售情况")
32         fig = pg.Figure(data=data, layout=layout)
33         plotly.offline.plot(fig, filename=output_path)
34 
35     finally:
36         if conn:
37             conn.close()
38 
39 
40 if __name__ == '__main__':
41     output_path = "C:/Users/fuqia/Desktop/bar.html"
42     bar_chart("localhost", 3306, "root", "123456", "test", "utf8", output_path)

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325341608&siteId=291194637