给定x和y值时,密度网格图旋转(Python)

时间:2017-07-21 10:45:36

标签: python matplotlib

我有一组数据点的网格密度图,当使用matplotlib 2dhistogram创建网格轮廓时,生成的颜色图似乎在垂直轴上翻转并旋转。我不明白为什么会出现这种情况,但我已将我的代码放在下面,并附上图片的图片。

import numpy as np
from ngtsio import ngtsio
import math 
from statsmodels import robust
from numpy import mean, absolute
from astropy.stats import LombScargle
import matplotlib.pyplot as plt

gridx = np.linspace(0,frac,21)
gridy = np.linspace(0,1,21)

grid,_,_ = np.histogram2d(new_phase,binned_flux,bins=[gridx,gridy])

plt.grid(True)
plt.pcolormesh(gridx,gridy,grid)
plt.colorbar()

plt.grid()
plt.plot(new_phase,binned_flux,'r.',linestyle='None',markersize = markersize)
plt.ylim(0,1)
plt.xlim(0,frac)
plt.xlabel('Phase')

请注意frac是一个(0.5,1.0,2.0)的数组,即在3个子图x轴中看到的限制,代码依次遍历每个和图。 enter image description here

非常感谢提前!

1 个答案:

答案 0 :(得分:2)

问题出现了,因为numpy.histogram2dmatplotlib.pyplot.pcolormesh解释了行和列的倒置。你可以通过一个非常简单的例子看到这一点,例如生成然后绘制单点的直方图(0.75,0.25),两个方向的箱子分别为0.0-0.5和0.5-1.0:

import numpy as np
import matplotlib.pyplot as plt

x = np.asarray([0.75])
y = np.asarray([0.25])
bin_edges = np.asarray([0.0, 0.5, 1.0])  # called gridx/gridy above
hist,_,_ = np.histogram2d(x, y, bins=[bin_edges, bin_edges]) 
                                         # called grid above
print(hist)
# array([[ 0.,  0.],
#        [ 1.,  0.]])
plt.gca().set_aspect("equal")
plt.pcolormesh(bin_edges, bin_edges, hist)
plt.scatter(x, y)
plt.show()

给出:

enter image description here

虽然histogram2d将行索引解释为x方向,将列索引解释为y方向(意味着列共享x值,行共享y值),但pcolormesh的反转为真{} 1}}。要获得正确的行为,您可以将plot命令更改为:

plt.gca().set_aspect("equal")
plt.pcolormesh(bin_edges, bin_edges, hist.T)
plt.scatter(x, y)
plt.show()

给出:

enter image description here