我想用我的数据实时绘制一条线matplotlib.animationpython模块。我的代码概述是,我正在计算一个分数a,并将其存储在一个列表中(“我的平均值”),这是y坐标。分数始终在-1和+1之间。此外,我希望我的x坐标是我的列表的长度“(len(my_average))”。例如,list收到一个分数x坐标将是列表的长度,因此1和y坐标将是分数,list接收第二个分数,list plots(1,score1)(2,score2)等。我无法显示图表,需要有关代码这部分的帮助。更进一步,如果可能的话,我不想从csv文件中读取列表,而是直接从内存中读取,并且仍然可以查看历史中以前的数据点。在
代码如下:from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
from textblob import TextBlob
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy
# Variables that contains the user credentials to access Twitter API
access_token =
access_token_secret =
consumer_key =
consumer_secret =
# This is a basic listener that just prints received tweets to stdout.
my_list = [] #creates empty list
my_average = []
class StdOutListener(StreamListener):
def on_data(self, data):
json_load = json.loads(data)
texts = json_load['text'] # string
#print(texts)
wiki = TextBlob(texts)
r = wiki.sentiment.polarity
my_list.append(r)
#drop zero in list
if 0 in my_list: my_list.remove(0)
print (my_list)
#calculate average
average = numpy.mean(my_list)
b = my_average.append(average)
#drop "nan" from list
if 'nan' in my_average: my_average.remove('nan')
print "average", my_average
fig = plt.figure()
ax = plt.axes(xlim=(0, 10), ylim=(0, -10))
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
x = (len(my_average))
y = (my_average)
line.set_data(x, y)
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,frames=100, interval=20, blit=True)
plt.show()
return True
def on_error(self, status):
print(status)
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
stream = Stream(auth, StdOutListener())
# This line filter Twitter Streams to capture data by the keywords: 'python', 'javascript', 'ruby'
stream.filter(track=['USD/CAD', 'Dollar', 'Loonie' ], languages=['en'])
提前谢谢你。在