contourf() breaks for 2-d array of datetime objects as axis - python

I am using matplotlib's contourf function to display z data as function of x and y. I am able to use a numpy array of datetime objects as the x-axis if x and y are 1-d arrays. However, When I make my x and y arrays 2-dimensional, contourf breaks on 2-d array of datetime objects. Example follows:
import numpy as np
from datetime import datetime,timedelta
import matplotlib.pyplot as plt
x = np.array([datetime(2012,12,12),datetime(2012,12,13),datetime(2012,12,14)])
y = np.arange(10)
z = np.random.random((10,3))
plt.contourf(x,y,z)
This example works and produces an expected result. However, if I do this:
x = np.tile(np.reshape(x,( 1,3)),(10,1))
y = np.tile(np.reshape(y,(10,1)),( 1,3))
so that x, y, and z are all of shape (10,3), contourf(x,y,z) yields this traceback:
Traceback (most recent call last):
File "./test_2d_datetime.py", line 14, in <module>
plt.contourf(x,y,z)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2206, in contourf
ret = ax.contourf(*args, **kwargs)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/axes.py", line 7322, in contourf
return mcontour.QuadContourSet(self, *args, **kwargs)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/contour.py", line 1106, in __init__
ContourSet.__init__(self, ax, *args, **kwargs)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/contour.py", line 700, in __init__
self._process_args(*args, **kwargs)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/contour.py", line 1119, in _process_args
x, y, z = self._contour_args(args, kwargs)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/contour.py", line 1166, in _contour_args
x,y,z = self._check_xyz(args[:3], kwargs)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/matplotlib/contour.py", line 1194, in _check_xyz
x = np.asarray(x, dtype=np.float64)
File "/home/disk/mako/milan/epd/epd-7.3-1-rh5-x86_64/lib/python2.7/site-packages/numpy/core/numeric.py", line 235, in asarray
return array(a, dtype, copy=False, order=order)
TypeError: float() argument must be a string or a number
If I use a 2-d array of matplotlib.dates.date2num() values instead of datetime objects, contourf() works as expected.
Is there a remedy for the problem I am encountering? I am using Python 2.7.3 with matplotlib 1.1.0 on 64-bit Linux.

Related

Supplied function does not return a valid float

import matplotlib.pyplot as plt
import numpy as np
import math
from scipy import *
from scipy.integrate import quad, dblquad, tplquad
q=range(1,6)
L=range(1,6)
sigmak=range(1,6)
x_lower = -3000
x_upper = 3000
y_lower = -3000
y_upper = 3000 #Integrate range
def final(a,b): #final(a,b)=0 to be plotted on a-b plane
m=a
n=b
def f3(x,y):
mass=0
for i in range(len(q)):
mass+=(L[i]*exp(-(x*x+y*y/(q[i]*q[i]))/(2*sigmak[i]*sigmak[i])))/(2*3.1415926*q[i]*sigmak[i]*sigmak[i])
return mass*(m-x)/((x-m)**2+(y-n)**2)
val=dblquad(f3,x_lower, x_upper, lambda x : y_lower, lambda x: y_upper)
return val[0]
y,x=np.ogrid[-1000:1000:200j,-1000:1000:200j]# plot range
f=final(x,y)
plt.figure(figsize=(9,4))
plt.subplot(121)
extent=[np.min(x),np.max(x),np.min(y),np.max(y)]
cs=plt.contour(f,extent=extent,levels=[0,0.1],colors=["b","r"],linestyles=["solid","dashed"],linewidths=[2,2])
plt.show()
Above is my codes. And I want to plot final(x,y)=0 in a plane. final(x,y) is a function which is a little complicated.When I run my code, it raises
Traceback (most recent call last):
File "test.py", line 25, in <module>
f=final(x,y)
File "test.py", line 22, in final
val=dblquad(f3,x_lower, x_upper, lambda x : y_lower, lambda x: y_upper)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/integrate/quadpack.py", line 433, in dblquad
return quad(_infunc,a,b,(func,gfun,hfun,args),epsabs=epsabs,epsrel=epsrel)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/integrate/quadpack.py", line 252, in quad
retval = _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/integrate/quadpack.py", line 317, in _quad
return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/integrate/quadpack.py", line 381, in _infunc
return quad(func,a,b,args=myargs)[0]
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/integrate/quadpack.py", line 252, in quad
retval = _quad(func,a,b,args,full_output,epsabs,epsrel,limit,points)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/scipy/integrate/quadpack.py", line 317, in _quad
return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
quadpack.error: Supplied function does not return a valid float.
So what's my problem? Thank you if anyone could help me!
Not sure what you are trying to do here
dblquad returns 2 floats, the resultant integral and an estimate of the error.
By making a for loop like below we can export an array but i don't think that's what you need
def final(a,b): #final(a,b)=0 to be plotted on a-b plane
outcome = []
for i in range(len(a)):
#print(i)
print(a[i])
m=a[i]
n=b[i]
def f3(x,y):
mass=0
for i in range(len(q)):
mass+=(L[i]*exp(-(x*x+y*y/(q[i]*q[i]))/(2*sigmak[i]*sigmak[i])))/(2*3.1415926*q[i]*sigmak[i]*sigmak[i])
return mass*(m-x)/((x-m)**2+(y-n)**2)
val=dblquad(f3,a[0], a[-1], lambda x : m, lambda x: a[-1])
outcome.append(val)
return np.array(outcome)
y=np.ogrid[-10:10:10j]
x=np.ogrid[-10:10:10j]
f=final(x,y)
Be more precise in what you are trying to achieve.

Librosa feature tonnetz ends up in TypeError

I'm trying to extract tonnetz from the harmonic components of my audio. My code is basically a copy paste from the tutorial https://librosa.github.io/librosa/generated/librosa.feature.tonnetz.html
My code:
import librosa
def extract_feature(file_name):
y, sr = librosa.load(file_name)
y = librosa.effects.harmonic(y)
tonnetz = librosa.feature.tonnetz(y=y, sr=sr)
return tonnetz
print extract_feature("out.wav")
Here's the stack trace:
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/core/pitch.py:160: DeprecationWarning: object of type <type 'numpy.float64'> cannot be safely interpreted as an integer.
bins = np.linspace(-0.5, 0.5, np.ceil(1./resolution), endpoint=False)
Traceback (most recent call last):
File "test_python.py", line 10, in <module>
print extract_feature("out.wav")
File "test_python.py", line 6, in extract_feature
tonnetz = librosa.feature.tonnetz(y=y, sr=sr)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/feature/spectral.py", line 1157, in tonnetz
chroma = chroma_cqt(y=y, sr=sr)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/feature/spectral.py", line 936, in chroma_cqt
real=False))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/core/constantq.py", line 251, in cqt
cqt_resp.append(__cqt_response(my_y, n_fft, my_hop, fft_basis))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/core/constantq.py", line 531, in __cqt_response
D = stft(y, n_fft=n_fft, hop_length=hop_length, window=np.ones)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/core/spectrum.py", line 167, in stft
y_frames = util.frame(y, frame_length=n_fft, hop_length=hop_length)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/librosa/util/utils.py", line 102, in frame
strides=(y.itemsize, hop_length * y.itemsize))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/lib/stride_tricks.py", line 102, in as_strided
array = np.asarray(DummyArray(interface, base=x))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/core/numeric.py", line 531, in asarray
return array(a, dtype, copy=False, order=order)
TypeError: 'float' object cannot be interpreted as an index
Any idea how to fix this?
I rolled back to numpy 1.10.1 to fix this issue (although I was running chroma_cqt and getting this error).
Numpy > 1.11 as_strided makes a dummyarray and asarray does not handle the float array properly. 1.10.1 numpy has better stride_tricks, apparently.

ValueError: matrix must be 2-dimensional

I have following codes to plot a gassian-2d contour,but I get this Error:
Traceback (most recent call last):
File "question.py", line 15, in <module>
Z0=gaussian_2d(X0,Y0,2,3,cov)
File "question.py", line 4, in gaussian_2d
return exp(-0.5*mat([x-x0,y-y0])*sigmaMatrix.I*mat([x-x0,y-y0]).T)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/matrixlib/defmatrix.py", line 96, in asmatrix
return matrix(data, dtype=dtype, copy=False)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/matrixlib/defmatrix.py", line 272, in __new__
raise ValueError("matrix must be 2-dimensional")
ValueError: matrix must be 2-dimensional
This my code:
import matplotlib.pyplot as plt
from numpy import *
def gaussian_2d(x, y, x0, y0, sigmaMatrix):
return exp(-0.5*mat([x-x0,y-y0])*sigmaMatrix.I*mat([x-x0,y-y0]).T)
cov=mat([[1,0],[0,2]])
delta=0.025
xgrid=arange(-2, 6, delta)
ygrid=arange(-2, 6, delta)
X0, Y0 = meshgrid(xgrid, ygrid)
Z0=gaussian_2d(X0,Y0,2,3,cov)
Can anyone tell me what am i doing wrong here?
Error starts from the concatenation but also your matrix dimensions don't match.
You are performing a quadratic form multiplication x^T A x but your meshgrid variables are square matrices of 320x320. Your A matrix cov is 2x2 hence you get an error.
If the sizes matches you can column concatenate mat(c_[x-x0,y-y0]) or use any other stacking option.

Python Matplotlib Hist2d with 2d array

I want to make a 2d histogramme by putting two 2D array as argument, Tx and alt_array, same size (56000,40)
def histo_2D(alt, Tx):
u,v = 56000,40
Tx = np.zeros((u,v))
alt_array = np.zeros((u,v))
alt,tx = np.zeros((v)), np.zeros((v))
for i in range(0,v):
alt[i] = i
tx[i] = i
alt_array[:][:] = alt
Tx[:][:] = tx
alt_array[:][:] = alt
print np.shape(Tx), np.shape(alt_array)
plt.hist2d(Tx , alt_array)
But when i try to execute my program, i get this error message :
Traceback (most recent call last):
File "goccp.py", line 516, in <module>
histo_2D(alt,Tx)
File "goccp.py", line 376, in histo_2D
plt.hist2d(Tx , alt_array)
File "/Code/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2847, in hist2d
weights=weights, cmin=cmin, cmax=cmax, **kwargs)
File "/Code/anaconda/lib/python2.7/site-packages/matplotlib/axes.py", line 8628, in hist2d
normed=normed, weights=weights)
File "/Code/anaconda/lib/python2.7/site-packages/numpy/lib/twodim_base.py", line 650, in histogram2d
hist, edges = histogramdd([x, y], bins, range, normed, weights)
File "/Code/anaconda/lib/python2.7/site-packages/numpy/lib/function_base.py", line 288, in histogramdd
N, D = sample.shape
ValueError: too many values to unpack
I've tried to use flattened array, but the result is not really good...
The documentation for hist2d states:
matplotlib.pyplot.hist2d(x, y, bins=10, range=None, normed=False, weights=None, cmin=None, cmax=None, hold=None, **kwargs)
Parameters: x, y: array_like, shape (n, ) :
Thus x and y need to be one dimensional; your values are two dimensional.
Have a look at the example as well, given at the end of the documentation.

Matplotlib: Quiver 2D array

i am struggling with the quiver function in python.
I want to create a 2D vector field of a given 2D array containing the two components of the vectors using quiver.
Given the array b:
>>> b
VigraArray(shape=(512, 512, 2), axistags=x y c, dtype=float32, data=
[[[ 0.59471679 0.51902866 0.38904327 ..., -0.56878477 -0.50834674
-0.48382956]
[ 0.58222073 0.50713873 0.37990916 ..., -0.56091702 -0.50057167
-0.47613338]
[ 0.53815156 0.46551338 0.34787226 ..., -0.54245669 -0.48314109
-0.45911735]
...,
and using quiver:
>>> X,Y = meshgrid(range(b.shape[0]),range(b.shape[1]))
>>> quiver(X,Y,b[...,0],b[...,1])
returns:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/pymodules/python2.7/matplotlib/pyplot.py", line 2892, in quiver
ret = ax.quiver(*args, **kw)
File "/usr/lib/pymodules/python2.7/matplotlib/axes.py", line 6641, in quiver
q = mquiver.Quiver(self, *args, **kw)
File "/usr/lib/pymodules/python2.7/matplotlib/quiver.py", line 419, in __init__
self.set_UVC(U, V, C)
File "/usr/lib/pymodules/python2.7/matplotlib/quiver.py", line 463, in set_UVC
U = ma.masked_invalid(U, copy=False).ravel()
File "/usr/lib/python2.7/dist-packages/numpy/ma/core.py", line 3969, in ravel
r._mask = ndarray.ravel(self._mask).reshape(r.shape)
File "/usr/lib/python2.7/dist-packages/vigra/arraytypes.py", line 1308, in reshape
res = numpy.ndarray.reshape(self, shape, order)
TypeError: an integer is required
I never had problems using VigraArray with matplotlib, so i don't think this is the problem. Thanks for help!
As a matter of fact it seems that pylab.quiver does not handle vigra.VigraArray correctly. The following substitution worked for me:
b[...,0] = numpy.array(b[...,0])
b[...,1] = numpy.array(b[...,1])

Categories

Resources