如前所說的,Plotly 在使用上非常困難,所以才會有plotly-express的產生。底下的代碼, 就是使用plotly展現台股每日大盤指數,可見得在撰寫上的確很麻煩。
#!/usr/bin/python3 import datetime import plotly.graph_objects as go import numpy as np import mysql.connector as mysql import plotly file='plotly_stock.html' conn=mysql.connect(host="ip",user="account", password="password", database="db") d=datetime.datetime.now() cmd="select * from taiex where tx_date >= '2016/01/01' order by tx_date" cursor=conn.cursor() cursor.execute(cmd) rows=cursor.fetchall() x=range(len(rows)) point=[] dates=[] for row in rows: point.append(row[5]) dates.append(row[1]) f=np.poly1d(np.polyfit(x,point,15)) reg=f(x) fig=go.Figure() fig.add_trace( go.Scatter( x=dates, y=point, mode='lines+markers', name='大盤指數', line=dict(color='royalblue', width=2) ) ) fig.add_trace( go.Scatter( x=dates, y=reg, mode='lines', name='日K線', line=dict(color='orange', width=2)) ) fig.update_layout( dragmode="pan", title_text="台灣股市分析", xaxis=go.layout.XAxis( rangeselector=dict( buttons=[ dict(count=1,label="1 month",step="month",stepmode="backward"), dict(count=6,label="6 month",step="month",stepmode="backward"), dict(count=1,label="1 year",step="year",stepmode="backward"), dict(count=1,label="1 day",step="day",stepmode="todate"), dict(step="all") ] ), rangeslider=dict(visible=True), type="date" ), yaxis=dict(fixedrange=False) ) #fig.show() plotly.offline.plot(fig,filename=file, auto_open=True) print('<iframe src="/python/plotly/{0}" width="800" height="650"></iframe>'.format(file))