解压缩Matplotlib hist2d输出的问题

时间:2018-01-29 10:11:00

标签: python matplotlib

我正在使用Matplotlib的函数hist2d(),我想解压缩输出以便进一步使用它。这就是我所做的:我只是用numpy加载一个包含我的数据的2列文件,并使用以下代码

import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np

traj = np.loadtxt('trajectory.txt')
x = traj[:,0]
y = traj[:,1]
M, xe, ye, img = plt.hist2d(x, y, bins = 80, norm = LogNorm())
plt.imshow(M)
plt.show()

我得到的结果如下:

Result obtained by unpacking the hist2d output and separately plotting the output matrix using imshow

相反,如果我尝试直接绘制hist2d结果而不解压缩它们:

import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np

traj = np.loadtxt('trajectory.txt')
x = traj[:,0]
y = traj[:,1]
plt.hist2d(x, y, bins = 80, norm = LogNorm())
plt.show()

我得到的整个情节没有奇怪的蓝盒子。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您可以直接使用plt.hist2d创建直方图。这将计算直方图并将其绘制到当前轴。没有必要再使用imshow显示它。

import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np; np.random.seed(9)

x = np.random.rayleigh(size=9900)
y = np.random.rayleigh(size=9900)

M, xe, ye, img = plt.hist2d(x, y, bins = 80, norm = LogNorm())

plt.show()

enter image description here

或者,您可以先计算直方图,然后将结果作为图像绘制到当前轴。请注意,numpy生成的直方图是转置的,请参阅Matplotlib 2D histogram seems transposed,因此需要调用imshow(M.T)。另请注意,为了获得正确的轴标记,您需要将imshow的{​​{1}}设置为extentxe边缘数组的极值。

ye

enter image description here