ax = plt.axes(projection=ccrs.Mercator()) give an error - python-3.x

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.

Related

Issue with FuncAnimation of matplotlib

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

How to customize a Graph using Matplotlib

I need help to customize a graph using Matplotlib.
I want to draw a graph like this.
My python code is:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
data=np.loadtxt('input.txt', delimiter = ',')
x = np.arange(0,64)
y = np.arange(0,64)
fig, ax = plt.subplots()
im = ax.imshow(data)
#customize colorbar
cmap = mpl.colors.ListedColormap(['royalblue','blue','red'])
im = ax.contourf(y,x,data,cmap=cmap)
fig.colorbar(im)
plt.show()
and my output is:
So what should i do ?
Thank you.

How can I solve " module 'pandas' has no attribute 'scatter_matrix' " error?

I'm trying to run pd.scatter_matrix() function in Jupyter Notebook with my code below:
import matplotlib.pyplot as plt
import pandas as pd
# Load some data
iris = datasets.load_iris()
iris_df = pd.DataFrame(iris['data'], columns=iris['feature_names'])
iris_df['species'] = iris['target']
pd.scatter_matrix(iris_df, alpha=0.2, figsize=(10, 10))
plt.show()
But I'm getting
AttributeError: module 'pandas' has no attribute 'scatter_matrix'.
Even after executing conda update pandas and conda update matplotlib commands in Terminal, this is still occurring.
I executed pd.__version__ command to check my pandas version and it's '0.24.2'. What could be the problem?
This method is under pandas.plotting - docs and pandas.plotting.scatter_matrix:
from pandas.plotting import scatter_matrix
scatter_matrix(iris_df, alpha=0.2, figsize=(10, 10))
Another option is keeping only pandas import and rewriting the command scatter_matrix, like in the example below:
import pandas as pd
pd.plotting.scatter_matrix(iris_df, alpha=0.2, figsize=(10, 10))
Using
from pandas.plotting._misc import scatter_matrix
don't use pd.scatter_matrix or pandas.scatter_matrix
you can directly call scatter_matrix
e.g.
cmap = cm.get_cmap('gnuplot')
scatter = scatter_matrix(X, c = y, marker = 'o', s=40, hist_kwds={'bins':15},
figsize=(9,9), cmap = cmap)
plt.suptitle('Scatter-matrix for each input variable')
plt.savefig('fruits_scatter_matrix')
plt.show()
Use:
from pandas.plotting import scatter_matrix
The code becomes:
import matplotlib.pyplot as plt
from pandas.plotting import scatter_matrix
iris = datasets.load_iris()
iris_df = pd.DataFrame(iris['data'], columns=iris['feature_names'])
iris_df['species'] = iris['target']
scatter_matrix(iris_df, alpha=0.2, figsize=(10, 10))
plt.show()
In our case we were executing below code "axs = pd.scatter_matrix(sampled_data, figsize=(10, 10)) "
so the error clearly says scatter_matrix is not available in pandas
Solution:
A bit of google and we found scatter_matrix is available in pandas.plotting
So correct code is "axs = pd.plotting.scatter_matrix(sampled_data, figsize=(10, 10)) "
I used
from pandas.plotting import scatter_matrix
and called scatter_matrix directly worked like charm.

pd.get_dummies syntax error python

I am getting an error while using pandas get_dummies command. Can someone point out why?
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('ggplot')
s = pd.read_csv('kddcup.txt')
t=s.apply(pd.Series.nunique)
print(t.index)
r = s.columns
print(r)
for n in range (0,len(t.index)):
if t[r[n]] == 1:
del s[r[n]
s = pd.get_dummies(s)//getting syntax error error here.
Spyder error code
You need to change del s[r[n] to del s[r[n]]. Each opening bracket must have a closing one.

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