Density plot using Matplotlib

Viewed 26

I am trying to do a density plot using the data in Text.txt but I am getting an error. I present the data in Test.txt, the code and the error below.

The data in Test.txt looks like

x    y         z
1   0.1     -1.18976
3   0.1     -0.95538
4   0.1     -1.1647
5   0.1     -1.11199
1   0.01    -1.02719
3   0.01    -0.83643
4   0.01    -0.94146
5   0.01    -0.97814
1   0.001   -1.27374
3   0.001   -1.58571
4   0.001   -1.65026
5   0.001   -1.62557

The code is

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
x, y, z = np.loadtxt('Test.txt', unpack=True)

plt.imshow(z,cmap=cm.hot)
plt.colorbar()
plt.show()

The error is

Traceback (most recent call last):

  File "C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Sept17_2022\Plotting\Plot.py", line 14, in <module>
    plt.imshow(z,cmap=cm.hot)

  File "C:\Users\USER\anaconda3\lib\site-packages\matplotlib\pyplot.py", line 2903, in imshow
    __ret = gca().imshow(

  File "C:\Users\USER\anaconda3\lib\site-packages\matplotlib\__init__.py", line 1361, in inner
    return func(ax, *map(sanitize_sequence, args), **kwargs)

  File "C:\Users\USER\anaconda3\lib\site-packages\matplotlib\axes\_axes.py", line 5609, in imshow
    im.set_data(X)

  File "C:\Users\USER\anaconda3\lib\site-packages\matplotlib\image.py", line 709, in set_data
    raise TypeError("Invalid shape {} for image data"

TypeError: Invalid shape (12,) for image data
1 Answers

As imshow requires a 2D-array, you have to reshape the data first. This would work:

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

x, y, z = np.loadtxt('Test.txt', unpack=True)
z = z.reshape((4,3))

plt.imshow(z,cmap=cm.hot)
plt.colorbar()
plt.show()

You probably want something more flexible with the shape depending on the input x- and y-data. But I don't know what information you have on the input data.

Related