i am currently working on a hobby project and got stuck on annotations in Matplotlib.
I have 2 Python files, one which scrapes the current price of a stock from yahoo and the current time. This information is then written in an csv:
from yahoo_fin import stock_info as si
import csv
import random
import time
from datetime import datetime
fieldnames = ['MSFTPrice', 'CurrentTime']
with open('MSFT.csv', 'w') as csv_file:
csv_writer = csv.DictWriter(csv_file, delimiter=',', lineterminator='\n', fieldnames= fieldnames)
csv_writer.writeheader()
count = 0
while True:
with open('MSFT.csv', 'a') as csv_file:
csv_writer = csv.DictWriter(csv_file, delimiter=',', lineterminator='\n', fieldnames= fieldnames)
MSFTPrice = si.get_live_price("MSFT")
count += 1.0
now = datetime.now()
CurrentTime = now.strftime("%H:%M:%S")
info = {
"MSFTPrice": '%.2f' %MSFTPrice,
"CurrentTime": CurrentTime}
csv_writer.writerow(info)
print('%.2f'%MSFTPrice, CurrentTime)
time.sleep(1)
if count >= 10000:
break
So the second one is then reading those 2 values and then creates a live visualization with matplotlib:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
plt.style.use('fivethirtyeight')
plt.style.use('dark_background')
def animate(i):
data = pd.read_csv('MSFT.csv')
x = data ["CurrentTime"]
y = data ["MSFTPrice"]
plt.cla()
plt.xlabel('Time')
plt.ylabel('Price')
plt.plot(x, y, color= 'green', linewidth=1.5)
plt.xticks(x[::300],fontsize= 12, rotation='horizontal')
for i,j in zip(x,y):
plt.annotate (str(j), xy = (i,j))
plt.tight_layout()
plt.grid(b=None)
ani = FuncAnimation(plt.gcf(), animate, interval=1000)
plt.tight_layout()
plt.show()
I want to annotate only the latest datapoint from the csv, but currently it annotate all datapoints. Here is a screenshot on how it looks now: Plot
Hope you can help me :)