[英]Density plot using Matplotlib
I am trying to do a density plot using the data in Text.txt
but I am getting an error.我正在尝试使用 Text.txt 中的数据进行密度Text.txt
,但出现错误。 I present the data in Test.txt
, the code and the error below.我在Test.txt
中显示数据,下面的代码和错误。
The data in Test.txt
looks like Test.txt
中的数据看起来像
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
As imshow
requires a 2D-array, you have to reshape the data first.由于imshow
需要二维数组,因此您必须先重塑数据。 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.根据输入的 x 和 y 数据,您可能想要更灵活的形状。 But I don't know what information you have on the input data.但我不知道您对输入数据有什么信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.