【问题标题】:matplotlib heatmap reversing data?matplotlib 热图反转数据?
【发布时间】:2013-03-20 10:07:30
【问题描述】:

这是一个奇怪的问题,希望有人能帮助我。我正在尝试使用 matplotlib 热图绘制我的数据的密度图,但不知何故,我的数据以一种奇怪的方式被反转/旋转。我有一个散点图,然后我将这些点合并为密度,但图像根本不是应该出现的。例如,这是原始散点图,其方向正确:

然后这是我的热图(请注意,结构从上方逆时针旋转了 90 度,但轴数据是正确的......轴上的数字是从数据中自动生成的,所以如果您只是将轴反转图片正确显示,但数字全部关闭):

我只是看不出这是怎么回事,因为数据解析例程与我刚刚生成散点图时的相同。我认为,它必须是热图的编码方式,但我看不出故障可能在哪里。我已经尝试过考虑热图的内置原点放置(左上角),但这并没有解决它。代码如下(先解析所有数据):

import numpy as np
from numpy import ndarray
import matplotlib.pyplot as plt
import matplotlib
import atpy
from pylab import *

twomass = atpy.Table()

twomass.read('/Raw_Data/IRSA_downloads/2MASS_GCbox2.tbl')


hmag = list([twomass['h_m']])
jmag = list([twomass['j_m']])
hmag = np.array(hmag)
jmag = np.array(jmag)
colorjh = np.array(jmag - hmag)

idx_c = (colorjh > -1) & (colorjh < 6)  #manipulate desired color quantities here
idx_h = (hmag > 8) & (hmag < 18)
idx = idx_c & idx_h

现在这里是热图代码:

heatmap, xedges, yedges = np.histogram2d(colorjh[idx], hmag[idx], bins=500)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

plt.clf()
plt.imshow(heatmap, extent=extent)

plt.xlabel('Color(J-H)', fontsize=15)           #adjust axis labels here
plt.ylabel('Magnitude (H)', fontsize=15)

plt.gca().invert_yaxis()

plt.legend(loc=2)
plt.title('CMD for Galactic Center (2MASS)', fontsize=20)
plt.grid(True)
plt.show()

我对 Python 还是很陌生,所以解释越少,我就越有可能好好利用它。感谢大家提供的任何帮助。

【问题讨论】:

    标签: python numpy matplotlib heatmap astronomy


    【解决方案1】:

    您的问题似乎与np.histogram2d 的工作方式有关。来自documentation

    请注意,直方图不遵循笛卡尔约定,其中 x 值在横坐标上,y 值在纵坐标轴上。相反,x 沿数组的第一维(垂直)进行直方图,y 沿数组的第二维(水平)绘制。这确保了与histogramdd 的兼容性。

    使用

    extent = [yedges[0], yedges[-1], xedges[-1], xedges[0]]
    

    应该给你你所期望的。如果您想保持与散点图相同的方向,也可以在您的 histogram2d 调用中反转 colorjh[idx]hmag[idx]

    【讨论】:

    • 这样就行了!非常感谢。 (对于后代,我会注意到 plt.gca().invert_yaxis() 代码不再需要,因为修改后的“范围”编码会进行轴反转。
    猜你喜欢
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 2018-05-09
    • 2020-12-15
    • 2021-01-14
    相关资源
    最近更新 更多