我正在尝试绘制频谱图。我在 matplotlib 中使用 imshow
。
问题是这样的,我正在从用 C++ 生成的文本文件中读取数据(它实质上创建了一个 2D 向量并将其存储到文本文件中),然后我读入文本文件并绘图。
下面是我生成的绘图的输出(从 C++ 导入到 python):
这是一个频谱图,实际上是用 Python 编写的(使用 matplotlib):
如您所见,x 轴和 y 轴互换了,这让我得到了错误的实际频谱图形状。
为什么会这样?例如,我是否一开始就读入了错误的数据并且发生了这种情况?或者,可能是我没有设置 x、y 轴本身?
任何帮助将不胜感激
编辑:
我使用这个函数读取数组:
def split_at_empty_lines(filename):
with open(filename) as f:
arr = []
for line in f:
if not line.strip() and arr:
yield arr
arr = []
elif line.strip(): arr.extend(float(x) for x in line.split())
if arr: yield arr;
频谱图是通过执行以下操作生成的:
a = list(split_at_empty_lines("file.txt");
hm = ax.imshow(a, interpolation='nearest',origin='lower',aspect='auto')
结果如下:
[[ 26.9287 30.9089 34.9285 ..., 23.016 28.9027 36.4073]
[ 26.7964 26.8524 32.7296 ..., 22.9524 28.6145 33.7204]
[ 26.4222 27.0941 29.094 ..., 22.5309 27.6803 26.7073]
...,
[ 25.9362 25.8307 29.7039 ..., 22.0084 25.9855 28.9602]
[ 26.4222 27.0941 29.094 ..., 22.5309 27.6803 26.7073]
[ 26.7964 26.8524 32.7296 ..., 22.9524 28.6145 33.7204]]
结果如下:
我不知道为什么会得到如此不同的结果。
最佳答案
如果您使用 numpy
读取数据到 ndarray
中,您可以在绘图之前转置数组。
import numpy as np
a = np.array(split_at_empty_lines("file.txt"))
print(a.T)
应该产生
array([[1, 4],
[2, 5],
[3, 6]])
关于python - matplotlib- Y 轴和 X 轴交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21144385/