我跟随this tutorial使用matplotlib创建了一个图表动画。现在我想把这个图表嵌入到django项目中,我遵循了显示静态图像的this tutorial,而我想要一个动态图像。我对matplotlib非常了解,这是我在utilis.py中写的
import matplotlib.pyplot as plt
import base64
from io import BytesIO
import cryptocompare
from datetime import datetime
from matplotlib.animation import FuncAnimation
def get_graph():
buffer = BytesIO()
plt.savefig(buffer, format='svg')
buffer.seek(0)
image_svg= buffer.getvalue()
graph = base64.b64decode(image_svg)
graph = graph.decode('utf-8')
buffer.close()
return graph
#get price of cryptocurrency
def get_crypto_price(cryptocurrency,currency):
return cryptocompare.get_price(cryptocurrency,currency=currency)[cryptocurrency][currency]
#get fullname of the cryptocurrency
def get_crypto_name(cryptocurrency):
return cryptocompare.get_coin_list()[cryptocurrency]['FullName']
# set style
plt.style.use('seaborn')
#X: datetime objects, Y: price
x_vals = []
y_vals = []
#animate function evry second
def animate(i):
plt.switch_backend('AGG')
plt.figure()
x_vals.append(datetime.now())
y_vals.append(get_crypto_price('ETH', 'EUR'))
plt.cla()
#specify plot title
plt.title(get_crypto_name('ETH') + 'Price live plotting')
plt.gcf().canvas.set_window_title('Live Plotting ETH')
plt.xlabel('Date')
plt.ylabel('Price (EUR)')
#actual plottib
plt.plot_date(x_vals,y_vals,linestyle="solid",ms=0)
plt.tight_layout()
graph = get_graph()
return graph
#call animate function
ani = FuncAnimation(plt.gcf(), animate, interval=1000)
这是views.py
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from .utilis import animate
def index_view(request):
chart = animate()
return render(request, 'cryptochart/index.html', {'chart': chart})
这是index.html
{% if chart %}
<img src="data:image/svg;base64, {{chart|safe}}">
{% endif %}
如果我运行代码,我得到的错误是:
animate() missing 1 required positional argument: 'i'
但我不知道如何解决这个问题,提前谢谢
目前没有回答
相关问题 更多 >
编程相关推荐