开发者

Python: Type error when drawing contour plot

despite using the search function I've been unable to find an answer. I got two assumptions, but don't know in how far they may apply. Now the problem:

I'd like to plot a contour. For this I've got here the following python code:

import numpy as np
import matplotlib.pyplot as plt

xi=list_of_distance
yi=list_of_angle

x = np.arange(0,54,0.2)
y = np.arange(0,180,2.0)

Z = np.histogram2d(xi,yi,bins=(274,90))
X, Y = np.meshgrid(x, y)

plt.contour(X,Y,Z)
plt.ylabel('angles')
plt.xlabel('distance')
plt.colorbar()
plt.show()

xi and yi are lists containing float values. x and y are defining the 'intervals' ...for example: x generates a list with values from 0 to 54 in 0.2 steps y gen开发者_如何学Goerates a list with values from 0 to 180 in 2.0 steps

with Z I make use of the numpy function to create 2D-Histograms. Actually this seems to be the spot that causes trouble.

When the function plt.contour(X,Y,Z) is called, the following error message emerges:

... File "/usr/lib/pymodules/python2.7/numpy/ma/core.py", line 2641, in new _data = np.array(data, dtype=dtype, copy=copy, subok=True, ndmin=ndmin) ValueError: setting an array element with a sequence.

Now to the assumptions what may cause this problem:

  1. It seems like it expects an array but instead of an numpy-array it receives a list

or

  1. We got a row that is shorter than the others (I came to that thought, after a collegue ran into such an issue a year ago - there it has been fixed by figuring out that the last row was by 2 elements shorter than all others...)


As @rocksportrocker implies, you need to take into account that histogram2d returns the edges in addition to the histogram. Another detail is that you probably want to explicitly pass in a range, otherwise one will be chosen for you based on the actual min and max values in your data. You then want to convert the edges to cell centers for the plot. Something like this:


import numpy as np
import matplotlib.pyplot as plt

n = 1000000                     # how many data points
xmin, xmax = 0.0, 54.0          # distances
ymin, ymax = 0.0, 180.0         # angles

# make up some random data
xi=np.random.normal(xmax/2.0, xmax/4.0, n)
yi=np.random.normal(ymax/3.0, ymax/3.0, n)

Z, xedges, yedges = np.histogram2d(xi,yi, bins=(270,90), range=[[xmin, xmax], [ymin, ymax]])

# find the cell centers from the cell edges
x = 0.5*(xedges[:-1] + xedges[1:])
y = 0.5*(yedges[:-1] + yedges[1:])

# promote to 2D arrays
Y, X = np.meshgrid(y, x)

plt.contour(X,Y,Z)
plt.ylabel('angles')
plt.xlabel('distance')
plt.colorbar()
plt.savefig("hist2d.png")

yields a countour plot like this:

Python: Type error when drawing contour plot

but personally I wouldn't use contours in this case, since the histogram is likely to be noisy.


Your traceback indicates that the error does not raise from the call to matplotlib, it is numpy which raises the ValueError.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜