0

I have a .dat file whose structure is given by three columns that I suppose to refer to be x, y and z = f(x,y), respectively.

I want to make a density plot out of this data. While looking for some example that could help me out, I came across the following posts:

How to plot a density map in python?

matplotlib plot X Y Z data from csv as pcolormesh

What I have tried so far is the following:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

x, y, z = np.loadtxt('data.dat', unpack=True, delimiter='\t')
N = int(len(z)**.5)
z = z.reshape(N, N)
plt.imshow(z, extent=(np.amin(x), np.amax(x), np.amin(y), np.amax(y)),cmap=cm.hot)
plt.colorbar()
plt.show()

The file data can be accessed here: data.dat.

When I run the script above, it returns me the following error message:

cannot reshape array of size 42485 into shape (206,206)

Can someone help me to understand what I have done wrong and how to fix it?

  • 1
    Maybe you you post a larger extract from your error message, but superficially I would guess that this is caused by your `reshape` call - N is set to 206, but the input array is length 42485 and cannot be reshaped into this matrix (206*206 != 42485) – patrick Sep 03 '21 at 14:05

1 Answers1

1

The reason is that your data is not exactly 260*260, but your z is larger.

One option is to slice the z, but you are missing data when you are doing that. And if that is what you want you are no longer using your x,y values.

z = z[:N**2].reshape(N,N)

In the link you posted I saw this statement:

I assume here that your data can be transformed into a 2d array by a simple reshape. If this is not the case than you need to work a bit harder on getting the data in this form.

The assumption does not hold for your data.

3dSpatialUser
  • 2,034
  • 1
  • 9
  • 18
  • if I understood correctly, you just sliced z. Is that right? I proceeded and implemented the slicing into my previous code attempt, the output is very different from what I expected for the density plot. Would there be any way to get the data into a 2d array for z without slicing? Finally, probably a stupid comment but I didn't get why the assumption made in the other post for the other data does not hold for mine. If you can clarify it, I would really appreciate. – HeitorGalacian Sep 03 '21 at 17:02
  • First about the assumption: The assumption states that it is possible to transform your array to a 2d array *by a simple reshape*. Since that is not possible the assumption is not true. For your plot I would suggest that you use the x,y coordinates of your data, otherwise your reshaped data is possibly not valid since a simple reshape does not preserve your spatial cohesion. Maybe this post will direct you in the correct direction for a solution that more suits your expectation: https://stackoverflow.com/questions/27004422/contour-imshow-plot-for-irregular-x-y-z-data – 3dSpatialUser Sep 07 '21 at 15:48