如何将散景图转换为可从Django发送到Web客户端的图像?
这是我的views.py
from bokeh.charts import TimeSeries
def stock_chart(request):
pdata = DataReader('GOOG', 'yahoo', datetime(2015,1,1), datetime(2015,1,15))
xyvalues = pd.DataFrame(dict(
price=pdata['Adj Close'],
Date=pdata.index.values,
))
pt = TimeSeries(xyvalues, index='Date', legend=True,
title=symbol , ylabel='Stock Prices', width=400, height=200)
#fig=pt.savefig()??????????? Here i need to convert pt to an image.
return HttpResponse(fig)
urls.py
urlpatterns = patterns('',
url(r'^stock_chart/$', views.stock_chart, name="stock_chart"),
)
我建议使用bokeh.embed模块:
http://docs.bokeh.org/en/latest/docs/user_guide/embed.html#components
from bokeh.embed import components
script, div = components(pt)
然后,您只需将脚本和div插入到html模板中。
[萨拉·伯德(Sarah Bird)在Pycon的Django应用程序中嵌入散景图的演讲也很好:(https://us.pycon.org/2015/schedule/presentation/369/)
谢谢。可行!
in views.py
import pandas as pd
from bokeh.charts import Histogram
def stock_chart(request):
histo_xyvalues = pd.DataFrame(dict(normal=[1, 2, 3, 1], lognormal=[5, 4, 4, 1]))
hm = Histogram(histo_xyvalues, bins=5, title='Histogram' , width=300, height=300)
script, div = components(hm)
return HttpResponse(script+div)
in urls.py
...
url(r'^stock_chart/$', views.stock_chart, name="stock_chart"),
...
a call from javascript/jQuery is,
...
$.get('/stock_chart/', function(data){
$('#chart_area').append(data);
});
...