kilojoules
kilojoules

Reputation: 10083

matplotlib plot X Y Z data from csv as pcolormesh

I have data in a csv of this form:

X,Y,Z
0,0,0.0
0,1,0.0
1,0,1.0
1,1,0.55
2,0,4.0
2,1,3.216

I am not sure how to feed this data to pcolormesh. I think I have to use np.meshgrid but I'm not sure how to in this case.

dat = pd.read_csv('my_dat.csv')
plt.pcolormesh(dat['X'], dat['Y'], dat['Z'])
plt.show()

Results in Value error: need more than one value to unpack

I don't understand - why doesn't this just work?

Upvotes: 3

Views: 4453

Answers (1)

tmdavison
tmdavison

Reputation: 69136

Your data just needs to be reshaped. No need to use np.meshgrid here, since you already have an x and y coord for each cell.

If you have nx coordinates in x, and ny coordinates in y, then you can do this:

X = dat['X'].reshape(nx,ny).T
Y = dat['Y'].reshape(nx,ny).T
Z = dat['Z'].reshape(nx,ny).T

plt.pcolormesh(X,Y,Z)
plt.show()

Note that pcolormesh prefers that you have your x and y dimensions be one greater that the z dimension, since x and y define the edges of the cells, and z defines the colour at the cell centre. From the docs:

Ideally the dimensions of X and Y should be one greater than those of C; if the dimensions are the same, then the last row and column of C will be ignored.

So, in you example, the colours from the final row and column will be lost, unless you add a row and column of dummy cells with x and y coordinates 1 greater than your number of cells. An alternative might be to use plt.contourf, for which x, y, and z should be the same length.

Upvotes: 5

Related Questions