Python histogram of split() data - python

I am trying to make a histgramm over a text file containing floats:
import matplotlib.pyplot as plt
c1_file = open('densEst1.txt','r')
c1_data = c1_file.read().split()
c1_sum = float(c1_data.__len__())
plt.hist(c1_data)
plt.show()
The output of c1_data.__len__() works fine, but hist() throws:
C:\Python27\python.exe "C:/x.py"
Traceback (most recent call last):
File "C:/x.py", line 7, in <module>
plt.hist(c1_data)
File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 2958, in hist
stacked=stacked, data=data, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 1812, in inner
return func(ax, *args, **kwargs)
File "C:\Python27\lib\site-packages\matplotlib\axes\_axes.py", line 5995, in hist
if len(xi) > 0:
TypeError: len() of unsized object

The main reason the plt.hist call fails is because the argument c1_data is a list containing strings. When you open a file and read it the result will be a string containing the files contents:
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode).
Emphasis mine.
When you now split this long string you'll get a list containing strings:
Return a list of the words in the string, using sep as the delimiter string.
However a list of strings is not a valid input for plt.hist:
>>> import matplotlib.pyplot as plt
>>> plt.hist(['1', '2'])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
1 import matplotlib.pyplot as plt
----> 2 plt.hist(['1', '2'])
C:\...\lib\site-packages\matplotlib\pyplot.py in hist(x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, hold, data, **kwargs)
3079 histtype=histtype, align=align, orientation=orientation,
3080 rwidth=rwidth, log=log, color=color, label=label,
-> 3081 stacked=stacked, data=data, **kwargs)
3082 finally:
3083 ax._hold = washold
C:\...\lib\site-packages\matplotlib\__init__.py in inner(ax, *args, **kwargs)
1895 warnings.warn(msg % (label_namer, func.__name__),
1896 RuntimeWarning, stacklevel=2)
-> 1897 return func(ax, *args, **kwargs)
1898 pre_doc = inner.__doc__
1899 if pre_doc is None:
C:\...\lib\site-packages\matplotlib\axes\_axes.py in hist(***failed resolving arguments***)
6178 xmax = -np.inf
6179 for xi in x:
-> 6180 if len(xi) > 0:
6181 xmin = min(xmin, xi.min())
6182 xmax = max(xmax, xi.max())
TypeError: len() of unsized object
The solution:
You can simply convert it to a float-array:
>>> import numpy as np
>>> plt.hist(np.array(c1_data, dtype=float))

Pointing to an example using numpy ... easy and results are below with the code.
pandas will work too, split and data type are available on reading (even if is a column data), also you can read as a vector (depends of the size of data)/
# !/usr/bin/env python
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import numpy as np
# will be better to read with numpy because you use float ...
#a = np.fromfile(open('from_file', 'r'), sep='\n')
from_file = np.array([1, 2, 2.5]) #sample data a
c1_data = from_file.astype(float) # convert the data in float
plt.hist(c1_data) # plt.hist passes it's arguments to np.histogram
plt.title("Histogram without 'auto' bins")
plt.show()
plt.hist(c1_data, bins='auto') # plt.hist passes it's arguments to np.histogram
plt.title("Histogram with 'auto' bins")
plt.show()

Related

Getting error "unhashable type: 'numpy.ndarray' " while trying to plot vectors from two different .nc files

I have read two files using open_mfdataset. What I'm trying to do is create a vector plot for the wind stress data for which the i and j components are stored in two different files.
paths= [ "i stress.nc", "j stress.nc"]
DS=xr.open_mfdataset(paths)
DS
This is the data description
But while trying to do the vector plotting using quiver I'm getting this unhashable typeerror.
ax= plt.axes(projection=ccrs.PlateCarree())
U=DS.SOZOTAUX.mean(dim='TIME')
V=DS.SOMETAUY.mean(dim='TIME')
x="LON86_125"
y="LAT71_110"
X,Y=np.meshgrid(x,y)
plt.quiver(X,Y,U,V)
TypeError Traceback (most recent call last)
c:\Users\souga\OneDrive\Desktop\Python programs\Project.ipynb Cell 5 in <cell line: 8>()
5 y="LAT71_110"
6 X,Y=np.meshgrid(y,x)
----> 8 plt.quiver(X,Y,U,V)
File c:\Users\souga\anaconda3\lib\site-packages\matplotlib\pyplot.py:2788, in quiver(data, *args, **kwargs)
2786 #_copy_docstring_and_deprecators(Axes.quiver)
2787 def quiver(*args, data=None, **kwargs):
-> 2788 __ret = gca().quiver(
2789 *args, **({"data": data} if data is not None else {}),
2790 **kwargs)
2791 sci(__ret)
2792 return __ret
File c:\Users\souga\anaconda3\lib\site-packages\cartopy\mpl\geoaxes.py:310, in _add_transform.<locals>.wrapper(self, *args, **kwargs)
305 raise ValueError('Invalid transform: Spherical {} '
306 'is not supported - consider using '
307 'PlateCarree/RotatedPole.'.format(func.__name__))
309 kwargs['transform'] = transform
--> 310 return func(self, *args, **kwargs)
File c:\Users\souga\anaconda3\lib\site-packages\cartopy\mpl\geoaxes.py:1842, in GeoAxes.quiver(self, x, y, u, v, *args, **kwargs)
1840 x, y = np.meshgrid(x, y)
...
227 _api.check_isinstance((str, bytes), value=val)
228 if convertible:
229 # this will only be called so long as convertible is True.
TypeError: unhashable type: 'numpy.ndarray'
You're using matplotlib.pyplot.quiver, which expects arrays of numbers x, y, u, v. When you call the following:
x="LON86_125"
y="LAT71_110"
X,Y=np.meshgrid(x,y)
X and Y are 2D string arrays:
In [3]: X
Out[3]: array([['LON86_125']], dtype='<U9')
In [4]: Y
Out[4]: array([['LAT71_110']], dtype='<U9')
Instead, I think you're looking for something along the lines of
X, Y = np.meshgrid(DS['LON86_125'].values, DS['LAT71_110'].values)
That said, you might try xarray.Dataset.plot.quiver which can work directly with xarray objects, and does accept string arguments referring to the dataset's variable and coordinate names:
DS.mean(dim='TIME').plot.quiver(
x='LON86_125',
y='LAT71_110',
u='SOZOTAUX',
v='SOMETAUY',
)

How to plot a windrose when the wind direction is a categorical value

From Dataset Australia Rainfall, I'm trying to predict RainTomorrow. Here is my code given below :
Downloading dataset directly from Kaggle using opendatasets library
import opendatasets as od
dataset_url = 'https://www.kaggle.com/jsphyg/weather-dataset-rattle-package'
od.download(dataset_url)
Importing necessary libraries
import os
import pandas as pd
import numpy as np
import plotly.express as px
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
sns.set_style('darkgrid')
matplotlib.rcParams['font.size'] = 14
matplotlib.rcParams['figure.figsize'] = (10,6)
matplotlib.rcParams['figure.facecolor'] = '#00000000'
Loading Dataset
data_dir = './weather-dataset-rattle-package'
os.listdir(data_dir)
train_csv = data_dir + '/weatherAUS.csv'
raw_df = pd.read_csv(train_csv)
Explore WindGustDir variable
print('WindGustDir contains', len(raw_df['WindGustDir'].unique()), 'labels')
raw_df['WindGustDir'].unique()
raw_df.WindGustDir.value_counts()
pd.get_dummies(raw_df.WindGustDir, drop_first=True, dummy_na=True).head()
pd.get_dummies(raw_df.WindGustDir, drop_first=True, dummy_na=True).sum(axis=0)
Plotting Windrose
from windrose import WindroseAxes
ax = WindroseAxes.from_ax()
ax.bar(raw_df.WindGustDir, raw_df.Rainfall, normed=True, opening=0.8,
edgecolor='white')
ax.set_legend()
I am unable to figure out which columns should use with WindGustDir or if their is any other option of compare RainTomorrow and WindGustDir .
Error Message
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
e:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
57 try:
---> 58 return bound(*args, **kwds)
59 except TypeError:
TypeError: '<' not supported between instances of 'float' and 'str'
During handling of the above exception, another exception occurred:
TypeError Traceback (most recent call last)
<ipython-input-253-1a1f0fa6bf7a> in <module>
1 ax = WindroseAxes.from_ax()
----> 2 ax.bar(direction=df.WindGustDir, var=df.Rainfall, normed=True, opening=0.8, edgecolor='white')
3 ax.set_legend()
e:\Anaconda3\lib\site-packages\windrose\windrose.py in bar(self, direction, var, **kwargs)
547 """
548
--> 549 bins, nbins, nsector, colors, angles, kwargs = self._init_plot(
550 direction, var, **kwargs
551 )
e:\Anaconda3\lib\site-packages\windrose\windrose.py in _init_plot(self, direction, var, **kwargs)
359
360 # Set the global information dictionnary
--> 361 self._info["dir"], self._info["bins"], self._info["table"] = histogram(
362 direction, var, bins, nsector, normed, blowto
363 )
e:\Anaconda3\lib\site-packages\windrose\windrose.py in histogram(direction, var, bins, nsector, normed, blowto)
746 direction[direction >= 360.] = direction[direction >= 360.] - 360
747
--> 748 table = histogram2d(x=var, y=direction, bins=[var_bins, dir_bins], normed=False)[0]
749 # add the last value to the first to have the table of North winds
750 table[:, 0] = table[:, 0] + table[:, -1]
<__array_function__ internals> in histogram2d(*args, **kwargs)
e:\Anaconda3\lib\site-packages\numpy\lib\twodim_base.py in histogram2d(x, y, bins, range, normed, weights, density)
742 xedges = yedges = asarray(bins)
743 bins = [xedges, yedges]
--> 744 hist, edges = histogramdd([x, y], bins, range, normed, weights, density)
745 return hist, edges[0], edges[1]
746
<__array_function__ internals> in histogramdd(*args, **kwargs)
e:\Anaconda3\lib\site-packages\numpy\lib\histograms.py in histogramdd(sample, bins, range, normed, weights, density)
1071
1072 # Compute the bin number each sample falls into.
-> 1073 Ncount = tuple(
1074 # avoid np.digitize to work around gh-11022
1075 np.searchsorted(edges[i], sample[:, i], side='right')
e:\Anaconda3\lib\site-packages\numpy\lib\histograms.py in <genexpr>(.0)
1073 Ncount = tuple(
1074 # avoid np.digitize to work around gh-11022
-> 1075 np.searchsorted(edges[i], sample[:, i], side='right')
1076 for i in _range(D)
1077 )
<__array_function__ internals> in searchsorted(*args, **kwargs)
e:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in searchsorted(a, v, side, sorter)
1346
1347 """
-> 1348 return _wrapfunc(a, 'searchsorted', v, side=side, sorter=sorter)
1349
1350
e:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in _wrapfunc(obj, method, *args, **kwds)
65 # Call _wrapit from within the except clause to ensure a potential
66 # exception has a traceback chain.
---> 67 return _wrapit(obj, method, *args, **kwds)
68
69
e:\Anaconda3\lib\site-packages\numpy\core\fromnumeric.py in _wrapit(obj, method, *args, **kwds)
42 except AttributeError:
43 wrap = None
---> 44 result = getattr(asarray(obj), method)(*args, **kwds)
45 if wrap:
46 if not isinstance(result, mu.ndarray):
TypeError: '<' not supported between instances of 'float' and 'str'
It seems that the direction parameter must be numeric.
Create a dict where each key is a each direction in 'WindGustDir' and the corresponding value is a float in degrees.
.map the dict to df.WindGustDir and plot
Alternatively, create and plot a new column
df.insert(loc=8, column='WindGustDirDeg', value=df.WindGustDir.map(wind_dir_deg))
import pandas as pd
from windrose import WindroseAxes
import numpy as np
# load the downloaded data and dropna
df = pd.read_csv('weatherAUS/weatherAUS.csv').dropna(subset=['WindGustDir'])
# create a dict for WindGustDir to numeric values
wind_dir = ['E', 'ENE', 'NE', 'NNE', 'N', 'NNE', 'NW', 'WNW', 'W', 'WSW', 'SW', 'SSW', 'S', 'SSE', 'SE', 'ESE']
degrees = np.arange(0, 360, 22.5)
wind_dir_deg = dict((zip(wind_dir, degrees)))
# plot and map WindGustDir to the dict
ax = WindroseAxes.from_ax()
ax.bar(direction=df.WindGustDir.map(wind_dir_deg), var=df.Rainfall, normed=True, opening=0.8, edgecolor='white')
ax.set_legend()

How to pass date array to pcolor plot?

I have matrix-data where one axis relates to dates. However, I'm having problems passing this data on as an axis to pcolor. My dummy data is as follows:
In [219]: X = [datetime.date.today() + datetime.timedelta(days=i) for i in range(4)]
In [220]: Y = arange(5)
In [221]: Z = arange(4*5).reshape(4, 5)
The naive attemp pcolor(Y, X, Z) fails because pcolor does not like to get a list object:
In [222]: pcolor(Y, X, Z)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-222-1ece18b4bc13> in <module>()
----> 1 pcolor(Y, X, Z)
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/pyplot.py in pcolor(*args, **kwargs)
2926 ax.hold(hold)
2927 try:
-> 2928 ret = ax.pcolor(*args, **kwargs)
2929 draw_if_interactive()
2930 finally:
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/axes.py in pcolor(self, *args, **kwargs)
7545 shading = kwargs.pop('shading', 'flat')
7546
-> 7547 X, Y, C = self._pcolorargs('pcolor', *args, allmatch=False)
7548 Ny, Nx = X.shape
7549
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/axes.py in _pcolorargs(funcname, *args, **kw)
7357
7358 Nx = X.shape[-1]
-> 7359 Ny = Y.shape[0]
7360 if len(X.shape) != 2 or X.shape[0] == 1:
7361 x = X.reshape(1, Nx)
AttributeError: 'list' object has no attribute 'shape'
Converting it to an array containing datetime.date fails with TypeError: float() argument must be a string or a number, not 'datetime.date':
In [223]: pcolor(Y, numpy.array(X), Z)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-223-a00423a6d479> in <module>()
----> 1 pcolor(Y, numpy.array(X), Z)
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/pyplot.py in pcolor(*args, **kwargs)
2926 ax.hold(hold)
2927 try:
-> 2928 ret = ax.pcolor(*args, **kwargs)
2929 draw_if_interactive()
2930 finally:
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/axes.py in pcolor(self, *args, **kwargs)
7606 kwargs['antialiaseds'] = False
7607
-> 7608 collection = mcoll.PolyCollection(verts, **kwargs)
7609
7610 collection.set_alpha(alpha)
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/collections.py in __init__(self, verts, sizes, closed, **kwargs)
743 Collection.__init__(self, **kwargs)
744 self._sizes = sizes
--> 745 self.set_verts(verts, closed)
746
747 def set_verts(self, verts, closed=True):
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/collections.py in set_verts(self, verts, closed)
763 codes[0] = mpath.Path.MOVETO
764 codes[-1] = mpath.Path.CLOSEPOLY
--> 765 self._paths.append(mpath.Path(xy, codes))
766 else:
767 self._paths.append(mpath.Path(xy))
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/path.py in __init__(self, vertices, codes, _interpolation_steps, closed, readonly)
131 vertices = vertices.astype(np.float_).filled(np.nan)
132 else:
--> 133 vertices = np.asarray(vertices, np.float_)
134
135 if codes is not None:
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/numpy/core/numeric.py in asarray(a, dtype, order)
460
461 """
--> 462 return array(a, dtype, copy=False, order=order)
463
464 def asanyarray(a, dtype=None, order=None):
TypeError: float() argument must be a string or a number, not 'datetime.date'
Finally, converting it to a proper numpy.datetime64 object does not resolve the situation either, failing with Invalid type promotion:
In [224]: pcolor(Y, numpy.array(X, dtype="datetime64[D]"), Z)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-224-0ac06cfafa35> in <module>()
----> 1 pcolor(Y, numpy.array(X, dtype="datetime64[D]"), Z)
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/pyplot.py in pcolor(*args, **kwargs)
2926 ax.hold(hold)
2927 try:
-> 2928 ret = ax.pcolor(*args, **kwargs)
2929 draw_if_interactive()
2930 finally:
/export/data/home/gholl/venv/gerrit/lib/python3.4/site-packages/matplotlib/axes.py in pcolor(self, *args, **kwargs)
7577 X4[:, newaxis], Y4[:, newaxis],
7578 X1[:, newaxis], Y1[:, newaxis]),
-> 7579 axis=1)
7580 verts = xy.reshape((npoly, 5, 2))
7581
TypeError: invalid type promotion
What would be the correct way to proceed here? In the
Note that the answer to the question plotting date data with pcolor uses scatter, not pcolor, and therefore does not help in my situation.
Matplotlib uses simple floats to represent datetimes. Hence you have to convert them first and then tell the axis that is has to format the labels as dates. Matplotlib provides the function date2num for that:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
import numpy as np
# Your original data (with adapted sizes)
x = [datetime.date.today() + datetime.timedelta(days=i) for i in range(4)]
y = np.arange(5)
z = np.arange(3*4).reshape(3, 4).T
# Convert to numbers
x = mdates.date2num(x)
# Create the figure
fig, ax = plt.subplots(1,1)
plt.pcolor(x,y,z)
# Setup the DateFormatter for the x axis
date_format = mdates.DateFormatter('%D')
ax.xaxis.set_major_formatter(date_format)
# Rotates the labels to fit
fig.autofmt_xdate()
plt.show()
Some other remarks:
For pcolor the x and y vectors represent the corner points of the tiles. So they need to be 1 element longer than the data.
The documentation provides a nice overview of how to handle dates in matplotlib.
Result:

Error saving a numpy.ndarray as an image (.png) using matplotlib.pyplot.imsave

How can I export numpy.ndarray as a graphics file (png, jpg, ...)?
When I try the following:
test = zeros((500, 750, 3), dtype=numpy.uint8)
imsave('out.png',test)
I get this error:
TypeError: from_bounds() takes exactly 4 arguments (5 given)
Below is the complete error output:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-ff0e3e551b72> in <module>()
----> 1 imsave('out.png',test)
/usr/lib/pymodules/python2.7/matplotlib/pyplot.pyc in imsave(*args, **kwargs)
1751 #docstring.copy_dedent(_imsave)
1752 def imsave(*args, **kwargs):
-> 1753 return _imsave(*args, **kwargs)
1754
1755 def matshow(A, fignum=None, **kw):
/usr/lib/pymodules/python2.7/matplotlib/image.pyc in imsave(fname, arr, vmin, vmax, cmap, format, origin, dpi)
1229
1230 figsize = [x / float(dpi) for x in arr.shape[::-1]]
-> 1231 fig = Figure(figsize=figsize, dpi=dpi, frameon=False)
1232 canvas = FigureCanvas(fig)
1233 im = fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin)
/usr/lib/pymodules/python2.7/matplotlib/figure.pyc in __init__(self, figsize, dpi, facecolor, edgecolor, linewidth, frameon, subplotpars)
266 self.dpi_scale_trans = Affine2D()
267 self.dpi = dpi
--> 268 self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
269 self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans)
270
TypeError: from_bounds() takes exactly 4 arguments (5 given)
The cause of the error you're seeing is this line in the traceback:
1230 figsize = [x / float(dpi) for x in arr.shape[::-1]]
Your array is 3-dimensional, so figsize will be a list of length 3. Later on, this list gets unpacked in the arguments to Bbox.from_bounds():
--> 268 self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)
Bbox.from_bounds() expects 4 arguments, but since the length of figsize is 3, it will get 5 arguments instead, hence the error.
This bug only affects RGB(A) image arrays, and was fixed in this commit - If you update your version of matplotlib to 1.3.1 or newer, the problem will go away.
Of course, there are lots of other ways to save numpy arrays to image files, and you could always use PIL (as in #enrico.bascis's answer), or one of the other methods from the question that #JohnZwink linked to instead.
You can use PIL:
import Image
import numpy as np
test = np.zeros((500, 750, 3), np.int8)
im = Image.fromarray(test, 'RGB')
im.save('test.png')

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

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.

Categories

Resources