python - 实时绘制动态 DataFrame 的两列
问题描述
我正在尝试绘制加载到数据框中的实时数据。但是这些尝试导致打印多个空白图表帧以响应动态数据馈送,而不是在单帧图表中绘制数据。
我正在实施一种解决方案来对实时 Twitter 流执行情绪分析。我能够流式传输推文,将它们放入 DataFrame 并一一应用所需的情绪分析算法。我在 DataFrame 中创建了一个列,其中包含该算法为单个推文生成的复合值。
这个 DataFrame 会随着推文流而动态更新,目的是根据时间绘制这个实时更新的复合值。
我已经尝试按照使用 plt.ion()、plt.draw() 而不是 plt.show() 函数等的建议绘制图表。但是,程序没有绘制用值更新的帧,而是开始打印随着数据在 DataFrame 中更新,多个帧一个接一个。
import pandas as pd
import csv
from bs4 import BeautifulSoup
import re
import tweepy
import ast
from pytz import timezone
from datetime import datetime
import matplotlib.pyplot as plt
import time
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import json
from textblob import TextBlob
from unidecode import unidecode
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
ckey= '#######'
csecret= '#######'
atoken= '#########'
asecret= '#########'
class listener(StreamListener):
def on_data(self,data):
try:
global df
data=json.loads(data)
time = data["created_at"]
tweet = unidecode(data["text"])
tweet1 = BeautifulSoup(tweet,"lxml").get_text()
df = pd.DataFrame(columns = ['time','tweet'])
df['time'] = pd.Series(time)
df['tweet'] = pd.Series(tweet1)
def convert_time(time):
eastern = timezone('US/Eastern')
utc = timezone('UTC')
created_at = datetime.strptime(time, '%a %b %d %H:%M:%S %z %Y')
est_created_at = created_at.astimezone(eastern)
return (est_created_at)
df['time'] = df['time'].apply(convert_time)
def hour(time):
hour = pd.DatetimeIndex(time).hour
return hour
df['hour'] = df['time'].apply(hour)
def sentiment_analysis(tweet):
sid = SentimentIntensityAnalyzer()
return (sid.polarity_scores(tweet)['compound'])
df['compound'] = df['tweet'].apply(sentiment_analysis)
#print(df['compound'])
#print(df['time'])
plt.ion()
fig, ax = plt.subplots()
df.plot(y=df'compound', ax=ax)
ax.clear()
ax.axis([ 0, 24, -5,5])
plt.xlabel('Time')
plt.ylabel('Sentiment')
plt.draw()
plt.pause(0.2)
except KeyError as e:
print(str(e))
return (True)
auth=OAuthHandler(ckey,csecret)
auth.set_access_token(atoken,asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["######"])
预期结果 - 一帧图形得到更新并绘制实时数据。
实际结果 - 多个空白图表
如果我错过了任何信息/要点,我深表歉意。
解决方案
推荐阅读
- date - 无法将参数转换为日期格式
- php - Angular PHP发送名称和文件
- mysql - 在 MySQL 中,如何复制表中的现有记录和依赖于父表 ID 的支持表?
- python - 在 Python 中对不同长度的直方图进行聚类
- sql-server - SQL Server 作为分布式缓存机制何时值得?
- react-native - React Native:道具警告,无效的道具值
- java - 如何在 Java Eclipse 中将列 JTable 添加到 Jcombobox
- r - 在 mutate() 中使用 get() 根据向量中的值添加列
- c - 如何使用c查找字符串中的文章数?
- java - 是否可以在谷歌地图上确定最近的街道是什么?