basemap.maskoceans: 'float' object cannot be interpreted as an integer - python

I'm getting the error:
TypeError: 'float' object cannot be interpreted as an integer
when I call maskoceans. Why is this? I'm running python3.
from mpl_toolkits.basemap import Basemap
from mpl_toolkits.basemap import maskoceans
from mpl_toolkits.basemap import interp
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
import numpy as np
places = {
(-8.91508040128176, 52.23826465): 0,
(-6.45854802816101, 52.64127685): 21,
(-9.03867527891856, 52.78809005): 0,
(-8.70926037608263, 53.717247): 0,
(-6.8217677, 54.3303964): 0,
(-6.1658125, 53.5255827): 4
}
m = Basemap(llcrnrlon=-10.56, llcrnrlat=51.39, urcrnrlon=-5.34, urcrnrlat=55.43,
lat_1=30., lat_2=60., lat_0=53.41, lon_0=-7.95,
resolution="i")
x, y, values = np.array([(x, y, v) for (x, y), v in places.items()]).T
coords = np.stack((x, y)).T
x, y = np.mgrid[-11:-4:10j, 51:56:10j]
z = griddata(coords, values, (x, y), method='nearest')
mdata = maskoceans(x, y, z, resolution = 'h', grid = 10, inlands=True)
plt.contour(x[:,0], x[0,:], mdata.T,linewidths=0.5,colors='k',z=99)
plt.contourf(x[:,0], y[0,:], mdata.T,cmap=plt.cm.Purples, z=100)
Here's the full stacktrack:
Traceback (most recent call last):
File "plot.py", line 28, in <module>
mdata = maskoceans(x, y, z, resolution = 'h', grid = 10, inlands=True)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mpl_toolkits/basemap/__init__.py", line 5107, in maskoceans
_readlsmask(lakes=inlands,resolution=resolution,grid=grid)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/mpl_toolkits/basemap/__init__.py", line 5132, in _readlsmask
np.reshape(np.fromstring(lsmaskf.read(),dtype=np.uint8),(nlats,nlons))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 257, in reshape
return _wrapfunc(a, 'reshape', newshape, order=order)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 62, in _wrapfunc
return _wrapit(obj, method, *args, **kwds)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/core/fromnumeric.py", line 42, in _wrapit
result = getattr(asarray(obj), method)(*args, **kwds)
TypeError: 'float' object cannot be interpreted as an integer

If you use Python3, you need to do a simple change to this file:
"your_python3_install_directory/lib/python3.x/site-packages/mpl_toolkits/basemap/init.py"
Between line 5125 and 5130, find "nlats = nlons/2" and change it to "nlats = nlons//2".
This should solve the problem.

Related

matplotlib's contourf producing error in tikzplotlib

could someone point out to what is wrong with the following code?
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib import cm,colors
import tikzplotlib
max_r = 20
N_vorfs = 500
scalings = np.linspace(0.1, 5.*np.pi, N_vorfs)
X, Y = np.meshgrid(scalings, 2.*np.arange(1, max_r+1)-1.)
Z = np.arange(max_r*N_vorfs).reshape(X.shape)
fig, axs = plt.subplots(2, 1, gridspec_kw={'height_ratios': [3, 1]})
axs[0].contour(X, Y, Z)
print(tikzplotlib.get_tikz_code())
plt.show()
I get errors from tikzplotlib, namely
Traceback (most recent call last):
File ".../to_pgfplot.py", line 19, in <module>
print(tikzplotlib.get_tikz_code())
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 209, in get_tikz_code
data, content = _recurse(data, figure)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 353, in _recurse
data, children_content = _recurse(data, child)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 378, in _recurse
data, cont = _draw_collection(data, child)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_save.py", line 319, in _draw_collection
return _path.draw_pathcollection(data, child)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/tikzplotlib/_path.py", line 214, in draw_pathcollection
p = obj.get_paths()[0]
IndexError: list index out of range

how to solve 'Expect x to not have duplicates' with scipy?

i was trying to make curve as follows:
x = all_dat['rcs']
y = all_dat['Mean_Range']
xnew = np.linspace(x.min(), x.max(), 200)
cubic_interploation_model = interp1d(x, y, kind = "cubic")
y_=cubic_interploation_model(xnew)
pl.plot(xnew , y_)
but i was not getting a plot and end with an error:
Traceback (most recent call last):
File "C:\Users\xxx\PycharmProjects\pythonProject1\seq_2_final.py", line 268, in <module>
plot_alldata(df_all,p2)
File "C:\Users\xxx\PycharmProjects\pythonProject1\seq_2_final.py", line 201, in plot_alldata
cubic_interploation_model = interp1d(x, y, kind = "cubic")
File "C:\Users\xxx\PycharmProjects\pythonProject1\venv\lib\site-packages\scipy\interpolate\_interpolate.py", line 564, in __init__
self._spline = make_interp_spline(xx, yy, k=order,
File "C:\Users\xxx\PycharmProjects\pythonProject1\venv\lib\site-packages\scipy\interpolate\_bsplines.py", line 1295, in make_interp_spline
raise ValueError("Expect x to not have duplicates")
ValueError: Expect x to not have duplicates
Process finished with exit code 1
How to solve this issue?

Keep getting this same error with my code - TypeError: 'float' object cannot be interpreted as an integer

Have a section of code, but it says that my float can't be interpreted as an integer, i don't know how to change this though - anyone have an idea?
import numpy as np
import matplotlib.pyplot as plt
from pandas import DataFrame # to build our table of data from the video. import glob import pims # to import the video. from pims import pipeline # a decorator to allow dynamic loading of videos
import scipy.ndimage as nd # for Gaussian filter.
import trackpy as tp # for object tracking functions.
crop = (slice(100, 1000), slice(500, 1250), 0)
thresh = 130
x = glob.glob('/Users/charlieargent/Extended Report /Potassium nitrate 1 hour//')
def readvid(x):
frames = pims.Video(x)
return(frames)
#pipeline
def crop_frame(frame):
return frame[crop]
#pipeline
def filter_frame(frame):
return nd.filters.gaussian_filter( crop_frame(frame), [2, 2] )
#pipeline
def binary_inv_frame(frame):
return ( (255 - filter_frame(frame) > thresh)*255 ).astype('uint8')
for i in x:
find_cells = tp.batch( binary_inv_frame(readvid(i)), 21, minmass = 200, invert = False )
tracks = tp.link_df( find_cells, 25, memory = 0 )
tracks_long = tp.filter_stubs( tracks, 5 )
msds = tp.imsd( tracks_long, 1, 25 )
y = i.split("/")[-3], i.split("/")[-2], i.split("/")[-1]
msds.to_csv("{}.csv".format(y))
Error:
File "", line 1, in
runfile('/Users/charlieargent/Extended Report /Analysis/untitled1.py', wdir='/Users/charlieargent/Extended Report /Analysis')
File "/anaconda3/lib/python3.7/site-packages/spyder_kernels/customize/spydercustomize.py", line 786, in runfile
execfile(filename, namespace)
File "/anaconda3/lib/python3.7/site-packages/spyder_kernels/customize/spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/charlieargent/Extended Report /Analysis/untitled1.py", line 45, in
find_cells = tp.batch( binary_inv_frame(readvid(i)), 21, minmass = 200, invert = False )
File "/anaconda3/lib/python3.7/site-packages/slicerator/init.py", line 687, in process
return Pipeline(proc_func, *ancestors)
File "/anaconda3/lib/python3.7/site-packages/slicerator/init.py", line 415, in init
self._len = len(ancestors[0])
TypeError: 'float' object cannot be interpreted as an integer

Animating 3D scatter plot using Python mplotlib via serial data

I am trying to animate a 3D scatter plot using mplotlib in Python. I am able to graph the data and redraw every time, but this results in a frame rate of less than 1 FPS, and I need to scale to upwards of 30 FPS. When I run my code:
import serial
import numpy
import matplotlib.pyplot as plt #import matplotlib library
from mpl_toolkits.mplot3d import Axes3D
from drawnow import *
import matplotlib.animation
import time
ser = serial.Serial('COM7',9600,timeout=5)
ser.flushInput()
time.sleep(5)
ser.write(bytes(b's1000'))
x=list()
y=list()
z=list()
#plt.ion()
fig = plt.figure(figsize=(16,12))
ax = fig.add_subplot(111, projection="3d")
graph = ax.scatter(x,y,z, c='r',marker='o')
ax.set_xlim3d(-255, 255)
ax.set_ylim3d(-255, 255)
ax.set_zlim3d(-255, 255)
def generate():
while True:
try:
ser_bytes = ser.readline()
data = str(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
xyz = data.split(", ")
dx = float(xyz[0])
dy = float(xyz[1])
dz = float(xyz[2].replace(";",""))
x.append(dx);
y.append(dy);
z.append(dz);
graph._offset3d(x,y,z, c='r',marker='o')
except:
print("Keyboard Interrupt")
ser.close()
break
return graph,
ani = matplotlib.animation.FuncAnimation(fig, generate(), interval=1, blit=True)
plt.show()
I get the following error:
Traceback (most recent call last):
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\cbook\__init__.py", line 388, in process
proxy(*args, **kwargs)
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\cbook\__init__.py", line 228, in __call__
return mtd(*args, **kwargs)
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1026, in _start
self._init_draw()
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1750, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1772, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
TypeError: 'tuple' object is not callable
Traceback (most recent call last):
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\cbook\__init__.py", line 388, in process
proxy(*args, **kwargs)
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\cbook\__init__.py", line 228, in __call__
return mtd(*args, **kwargs)
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1308, in _handle_resize
self._init_draw()
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1750, in _init_draw
self._draw_frame(next(self.new_frame_seq()))
File "C:\Users\bunti\AppData\Local\Programs\Python\Python36-32\lib\site-packages\matplotlib\animation.py", line 1772, in _draw_frame
self._drawn_artists = self._func(framedata, *self._args)
TypeError: 'tuple' object is not callable
I am receiving x, y, z coordinates from a lidar module connected to an Arduino, which sends the coordinates over serial to the Python script.
A possible problem with your code is that the animation function (generate) is not supposed to run in an infinite loop. Furthermore, you are supposed to pass a reference to that function to FuncAnimate, but instead you are calling the function (i.e. you need to omit the parentheses in FuncAnimation(..., generate, ...)
The second problem is that you are treating graph._offset3d as if it was a function, when it is merely a tuple of lists. You should assign a new tuple to it, instead of trying to call the function (which I believe is what the error message alludes to).
I simplified your code and the following works fine:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.animation as animation
def update_lines(num):
dx, dy, dz = np.random.random((3,)) * 255 * 2 - 255 # replace this line with code to get data from serial line
text.set_text("{:d}: [{:.0f},{:.0f},{:.0f}]".format(num, dx, dy, dz)) # for debugging
x.append(dx)
y.append(dy)
z.append(dz)
graph._offsets3d = (x, y, z)
return graph,
x = [0]
y = [0]
z = [0]
fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(111, projection="3d")
graph = ax.scatter(x, y, z, color='orange')
text = fig.text(0, 1, "TEXT", va='top') # for debugging
ax.set_xlim3d(-255, 255)
ax.set_ylim3d(-255, 255)
ax.set_zlim3d(-255, 255)
# Creating the Animation object
ani = animation.FuncAnimation(fig, update_lines, frames=200, interval=50, blit=False)
plt.show()

Matplotlib ArtistAnimation gives TypeError: 'AxesImage' object is not iterable [duplicate]

This question already has answers here:
matplotlib imshow(): how to animate?
(2 answers)
Closed 6 years ago.
Can you please help me figuring out what the problem is here? I don't know what is going wrong. Single plots from img can be plotted just fine, but the animation module gives an error. The Traceback says:
Traceback (most recent call last):
File "/home/ckropla/workspace/TAMM/Sandkasten.py", line 33, in <module>
ani = animation.ArtistAnimation(fig, img, interval=20, blit=True,repeat_delay=0)
File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 818, in __init__
TimedAnimation.__init__(self, fig, *args, **kwargs)
File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 762, in __init__
*args, **kwargs)
File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 481, in __init__
self._init_draw()
File "/home/ckropla/.pythonbrew/pythons/Python-3.3.1/lib/python3.3/site-packages/matplotlib/animation.py", line 824, in _init_draw
for artist in f:
TypeError: 'AxesImage' object is not iterable
Code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def FUNCTION(p,r,t):
k_0,dx,c = p
x,y = r
z = np.exp(1j*(k_0[0]*np.meshgrid(x,y)[0]+k_0[1]*np.meshgrid(x,y)[1]-c*t))*np.exp(-((np.sqrt(np.meshgrid(x,y)[0]**2+np.meshgrid(x,y)[1]**2)-c*t)/(2*dx))**2 )*(2/np.pi/dx**2)**(1/4)
z = abs(z)
#k,F = FFT((x-c*t),y)
return(x,y,z)
#Parameter
N = 500
n = 20
x = np.linspace(-10,10,N)
y = np.linspace(-10,10,N)
t = np.linspace(0,30,n)
r=[x,y]
k_0 = [1,1]
dx = 1
c = 1
p = [k_0,dx,c]
fig = plt.figure("Moving Wavepackage")
Z = []
img = []
for i in range(n):
Z.append(FUNCTION(p,r,t[i])[2])
img.append(plt.imshow(Z[i]))
ani = animation.ArtistAnimation(fig, img, interval=20, blit=True,repeat_delay=0)
plt.show()
Each element in img needs to be a sequence of artists, not a single artist. If you change img.append(plt.imshow(Z[i])) to img.append([plt.imshow(Z[i])]) then your code works fine.

Categories

Resources