问题
I have the following code to plot a 2d histogram in pyplot:
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
MIN, MAX, num = .001, 5000, 500
minn=1
maxx=1000
zbins = 10 ** np.linspace(np.log10(MIN), np.log10(MAX), num)
x=np.linspace(100,600,50000)
y=np.linspace(0,500,50000)
fig1 = plt.figure(1)
counts1,xedges1,edges1,d=plt.hist2d(x,y,bins=zbins)
mesh1 = plt.pcolormesh(zbins, zbins, counts1)
plt.xlim([minn, maxx])
plt.ylim([minn, maxx])
plt.gca().set_xscale("log")
plt.gca().set_yscale("log")
plt.colorbar()
plt.show()
Apologies for my horrible variable naming!
Anyways, when I plot this, the histogram seems to have the x and y axes switched. I checked the matplotlib 2d hist documentation and I was sure that I had the x and y arguments in the right order, but I cannot for the life of me figure out where I'm going wrong. Any help would be greatly appreciated!
回答1:
The confusion comes from the fact that the returned counts array is not what you think it is.
plt.hist2d internally uses numpy.histogram2d to compute the two-dimensional histogram. The documentation states as return values:
H: ndarray, shape(nx, ny) The bi-dimensional histogram of samples x and y. Values in x are histogrammed along the first dimension and values in y are histogrammed along the second dimension.xedges: ndarray, shape(nx,) The bin edges along the first dimension.yedges: ndarray, shape(ny,) The bin edges along the second dimension.
Apart from the fact that there seems to be a mistake concerning the exact shape of the arrays, we see that the first dimension of the returned histogram array is x and the second y.
However, matplotlib always expects y to be the first dimenstion. Therefore, while plt.hist2d produces the correct plot, plt.pcolormesh needs a transposed version of the array.
plt.pcolormesh(X,Y, counts.T)
A full example, comparing plt.hist2d and plt.pcolormesh:
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(1,10,10)
y=np.linspace(6,9,10)
zbinsx= np.linspace(0,10,11)
zbinsy= np.linspace(5,10,6)
fig, (ax, ax2) = plt.subplots(ncols=2)
counts,xedges,yedges,d = ax.hist2d(x,y, bins=[zbinsx,zbinsy])
# counts has shape (10, 5)
X,Y = np.meshgrid(xedges,yedges)
mesh1 =ax2.pcolormesh(X,Y, counts.T)
plt.show()
来源:https://stackoverflow.com/questions/43568370/matplotlib-2d-histogram-seems-transposed