Issue with FuncAnimation of matplotlib - python-3.x

Appreciating your time and effort to go through my code and helping me to find the solution.
I am using FuncAnimation of Matplotlib to refresh/update my plot every 1min.
The Data is extracted using Yahoo finance every 1min. But I am getting following error:
in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
TypeError: 'NoneType' object is not callable
Below is my code:
import yfinance as yf
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def Get_Data():
Data = yf.download(tickers="VIPIND.NS",interval="1m", period="1d")
Data.reset_index(inplace = True)
Data['Datetime'] = Data['Datetime'].dt.tz_convert('Asia/Kolkata').dt.tz_localize(None)
Data['Datetime'] = pd.to_datetime(Data['Datetime'])
Data=Data.set_index('Datetime')
print("Refreshed")
plt.figure(1)
plt.cla()
plt.xticks()
plt.plot(Data['Close'], linewidth = 2)#,label = f'Close at {Data.index[-1]}')
plt.title(f'Close Price at {Data.index[-1]}')
plt.xlabel("Time")
plt.show()
return
LivePlot = FuncAnimation(plt.gcf(),Get_Data(),interval=60000)
Please guide me on where am I going wrong ? and how to resolve this issue.
Regards
Sudhir

Related

ax = plt.axes(projection=ccrs.Mercator()) give an error

I have the following program:
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
birddata = pd.read_csv("bird_tracking.csv")
bird_names = pd.unique(birddata.bird_name)
plt.figure(figsize=(10,10)
ax = plt.axis(projection=ccrs.Mercator())
ax.set_extent((-25.0,20.0,52.0,10.0))
ax.add_feature(cfeature.LAND)
ax.add_feature(cfeature.OCEAN)
ax.add_feature(cfeature.COASTLINE)
ax.add_feature(cfeature.BORDERS,linestyle=":")
for name in bird_names:
ix = birddata['bird_name'] == name
x, y = birddata.longitude[ix], birddata.latitude[ix]
ax.plot(x, y,".", transform = ccrs.Geodetic(), label = name)
plt.legend(loc="upper left")
plt.savefig("map.pdf")
I am using Spyder 5 and python 3.9. But I have an invalid syntax for the line ax = plt.axis(projection=ccrs.Mercator())
If I run the program, I receive this message in the console:
error in ax
I am unable to find help on this. Moreover, if you go to this link, you will see that they use it exactly as I do. So what am I missing?
Thank you i advance for your help.

Animation not working in matplotlib python

I am doing my first matplotlib animation graph. and It's not working.please someone explain me,why??
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import numpy as np
n = 100
X = np.random.randn(n)
def update(curr):
if curr == n:
a.event_source.stop()
plt.cla()
bins = np.arange(-4,4, 0.5)
plt.hist(X[:curr], bin=bins)
plt.axis([-4,4,0,30])
plt.annotate("n={}".format(curr),(3,27))
fig = plt.figure()
a = animation.FuncAnimation(fig, update, interval=100)
P.S. I am coding on jupyter notebook
I got my answer. It's a typo in plt.hist call. The parameter is bins not bin.
plt.hist(X[:curr], bins=bins)

"DataFrame" is not callable

It seems to be a recurrent problem on the site but i was not able to understand any of the similar problems/topics. I'm trying to get a scatter matrix from pandas (pandas.plotting.scatter_matrix), but I get the error DataFrame is not callable.
Sorry to bother you, the error is maybe obvious but I'm not able to deal with it.
I'm not very familiar with pandas.
#Data_set is data from load_iris from sklearn.datasets, it is a bunch and it
#has 5 keys : 'features_names','target_names','target','DESCR', 'data'
iris_df = pd.DataFrame(Data_set['data'], columns=Data_set['feature_names'])
iris_df['species'] = Data_set['target']
pd.plotting.scatter_matrix(iris_df, alpha=0.2, figsize=(10, 10))
plt.show()
I just want to print the scatter matrix of my data and I get the error DataFrame is not callable and I'm not able to understand why.
I can get the scatter_matrix without any problems using the following code:
from sklearn import datasets
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
pal = sns.color_palette("cubehelix", 8)
sns.set_palette(pal)
Data_set = datasets.load_iris()
iris_df = pd.DataFrame(Data_set['data'], columns=Data_set['feature_names'])
iris_df['species'] = Data_set['target']
pd.plotting.scatter_matrix(iris_df, alpha=0.2, figsize=(10, 10))
plt.show()
There's a possibility you haven't read in the data set correctly. Check the contents of your Data_set.

Matplotlib.animation.FuncAnimation using pcolormesh

Python 3.5, windows 10 Pro.
I'm trying to continuously plot an 8x8 array of pixels (for the sake of the question I'll just use random data, but in the real thing I'm reading from a serial port).
I can do it using a while loop, but I need to switch over to matplotlib.animation.FuncAnimation and I can't get it to work. I've tried looking at the help files and tried to follow examples from matplotlib.org here, but I've not been able to follow it.
Can someone help me figure out how to continuously plot an 8x8 array of pixels using FuncAnimation and pcolormesh? Here is what I've got so far:
import scipy as sp
import matplotlib.pyplot as plt
from matplotlib import animation
plt.close('all')
y = sp.rand(64).reshape([8,8])
def do_something():
y = sp.rand(64).reshape([8,8])
fig_plot.set_data(y)
return fig_plot,
fig1 = plt.figure(1,facecolor = 'w')
plt.clf()
fig_plot = plt.pcolormesh(y)
fig_ani = animation.FuncAnimation(fig1,do_something)
plt.show()
If you want to see the while loop code, just so you know exactly what I'm trying to reproduce, see below.
import scipy as sp
import matplotlib.pyplot as plt
plt.figure(1)
plt.clf()
while True:
y = sp.rand(64).reshape([8,8])
plt.pcolormesh(y)
plt.show()
plt.pause(.000001)
I was able to find a solution using imshow instead of pcolormesh. In case anyone else is struggling with the same issues I had, I've posted the working code below.
import scipy as sp
import matplotlib.pyplot as plt
import matplotlib.animation as animation
Hz = sp.rand(64).reshape([8,8]) # initalize with random data
fig = plt.figure(1,facecolor='w')
ax = plt.axes()
im = ax.imshow(Hz)
im.set_data(sp.zeros(Hz.shape))
def update_data(n):
Hz = sp.rand(64).reshape([8,8]) # More random data
im.set_data(Hz)
return
ani = animation.FuncAnimation(fig, update_data, interval = 10, blit = False, repeat = False)
fig.show()

Charting with Candlestick_OHLC

import pandas as pd
import numpy as np
from matplotlib.finance import candlestick_ohlc
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import io
import datetime
import urllib
import urllib.request
%matplotlib notebook
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/GOOG/chartdata;
type=quote;range=1y/csv'
with urllib.request.urlopen(urlToVisit) as response:
sourcePage = response.read().decode('utf-8')
df = pd.read_csv(io.StringIO(sourcePage), skiprows=18, header=None, sep=",",
names=['date','closeP','highP','lowP','openP','volume'],
index_col= 0, parse_dates= True)
if 'volume' not in df:
df['volume'] = np.zeros(len(df))
DATA = df[['openP', 'highP', 'lowP', 'closeP','volume']].values
f1 = plt.subplot2grid((6,4), (1,0), rowspan=6, colspan=4, axisbg='#07000d')
candlestick_ohlc(f1, DATA, width=.6, colorup='#53c156', colordown='#ff1717')
f1.grid('on')
f1.xaxis.set_major_locator(mticker.MaxNLocator(15))
f1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.subplots_adjust(left=.09, bottom=.14, right=.94, top=.95, wspace=.20, hspace=0)
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.show()
So here's the problem, when I try to plot the 'candlestick_ohlc' but it only plots the volume bar chart! (Why is this happening?) I'm thinking that maybe the problem has to do with my dates? I'm using iPython Notebook btw. My source is from - Yahoo Finance. If you notice, I skipped the first 18 lines so that I can get straight to the actual data itself and it looks like:
20150302,569.7757,570.5834,557.2202,558.9953,2129600
20150303,572.0694,573.8146,564.9689,568.8881,1704700
20150304,571.8001,575.5299,566.4548,570.3043,1876800
20150305,573.7548,576.3277,571.8400,573.4456,1389600
20150306,566.1307,575.1011,565.2082,573.3060,1659100
20150309,567.2925,568.7086,561.9921,565.3079,1062100
date,close,high,low,open,volume
Any ideas? Would appreciate any help!!
So with the help of #DSM,
DATA = df[['openP', 'highP', 'lowP', 'closeP','volume']]
DATA = DATA.reset_index()
DATA["date"] = DATA["date"].apply(mdates.date2num)
f1 = plt.subplot2grid((6,4), (1,0), rowspan=6, colspan=4, axisbg='#07000d')
candlestick_ohlc(f1, DATA.values, width=.6, colorup='#53c156', colordown='#ff1717')
fixed the problem! Credits to him.

Resources