Sanic 集成 Plotly#
plotly 有着丰富的可视化设计,比如:
from plotly import graph_objects as go
go.FigureWidget();
from sanic import Sanic
from sanic.response import html
import plotly
from plotly import express as px
z = [[.1, .3, .5, .7, .9],
[1, .8, .6, .4, .2],
[.2, 0, .5, .7, .9],
[.9, .8, .4, .2, 0],
[.3, .4, .5, .7, 1]]
fig = px.imshow(z, text_auto=True, aspect="auto")
fig
为了提供 Sanic 集成,需要借助 plotly.offline.plot
将 fig
转换为 HTML:
app = Sanic(__name__)
@app.route('/')
async def index(request):
return html(plotly.offline.plot(fig, auto_open=False, output_type='div'))
完整代码示例:
from sanic import Sanic
from sanic.response import html
import plotly
import plotly.express as px
app = Sanic(__name__)
@app.route('/')
async def index(request):
z = [[.1, .3, .5, .7, .9],
[1, .8, .6, .4, .2],
[.2, 0, .5, .7, .9],
[.9, .8, .4, .2, 0],
[.3, .4, .5, .7, 1]]
fig = px.imshow(z, text_auto=True, aspect="auto")
return html(plotly.offline.plot(fig, auto_open=False, output_type='div'))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, dev=True)