python - 对数二维 - 使用 matplotlib 的直方图

标签 python numpy matplotlib

这是我的第一个 python 程序,所以我的程序中可能有些“有趣”的东西。该程序从它在给定目录中找到的文件中读取 3 列。然后计算每个文件的直方图,并将结果添加到二维矩阵以创建类似 2D-Hist 的东西。

我的困难在于我的第三个情节,我希望 y 轴数据采用对数刻度,并根据该刻度呈现数据。此外,我想从我的输入条目中删除“零”条目。我尝试为此使用 numpy.where(matrix),但我不知道这是否真的符合我的要求...

这是我的代码:

#!/usr/bin/python
# Filename: untitled.py
# encoding: utf-8

from __future__ import division
from matplotlib.colors import LogNorm
import matplotlib
import numpy as np
import matplotlib.pylab as plt
import os
import matplotlib.cm as cm

def main():

   dataFiles = [filename for filename in os.listdir(".") if (filename[-4:]==".log" and filename[0]!='.')]
   dataFiles.sort()

   p = []
   matrix1 = []
   matrix2 = []
   matrix3 = []

   for dataFile in dataFiles:
            p += [ eval(dataFile[11:16]) ]
            data = np.loadtxt(dataFile, skiprows=7)[:,1:4]

            matrix1 += [ data[:,0] ]
            matrix2 += [ data[:,1] ]
            matrix3 += [ data[:,2] ]

    matrixList = [matrix1, matrix2, matrix3]

    #make histograms out of the matrices
    matrix1Hist = [  np.histogram( matrixColumn, bins=30,  range=(np.min(np.where(matrix1 != 0)), np.max(matrix1)))[0]   for matrixColumn in matrix1 ]
    matrix2Hist = [  np.histogram( matrixColumn, bins=200, range=(np.min(np.where(matrix2 != 0)), np.max(matrix2)))[0]   for matrixColumn in matrix2 ]
    matrix3Hist = [  np.histogram( matrixColumn, bins=50,  range=(np.min(np.where(matrix3 != 0)), np.max(matrix3)))[0]   for matrixColumn in matrix3 ]

    # convert the matrixHistogramsto numpy arrays and swap axes
    matrix1Hist = np.array(matrix1Hist).transpose()
    matrix2Hist = np.array(matrix2Hist).transpose()
    matrix3Hist = np.array(matrix3Hist).transpose() 

    matrixHistList = [matrix1Hist, matrix2Hist, matrix3Hist]

    fig = plt.figure(0)
    fig.clf()

    for i,matrixHist in enumerate( [matrix1Hist, matrix2Hist, matrix3Hist] ):
            ax = fig.add_subplot(2, 2, i+1)
            ax.grid(True)
            ax.set_title('matrix'+str(i+1))
            if i < 2:
                   result = ax.imshow(matrixHist,
                                      cmap=cm.gist_yarg,
                                      origin='lower',
                                      aspect='auto', #automatically span matrix to available space
                                      interpolation='hanning',
                                      extent= [ p[0], p[-1], np.floor( np.min( matrixList[i])), np.ceil( np.max( matrixList[i])) ] ,
                                      )

            elif i == 2:
                    result = ax.imshow(matrixHist,
                                       cmap=cm.gist_yarg,
                                       origin='lower',
                                       aspect='auto', #automatically span matrix to available space
                                       interpolation='hanning',
                                       extent= [ p[0], p[-1], 1, np.log10(np.max( matrixList[i])) ] ,
                                       )


            ticks_at = [ 0 , abs(matrixHist).max()]
            fig.colorbar(result, ticks=ticks_at,format='%1.2g')


    plt.show()


if __name__ == '__main__':
    main()

最佳答案

对于问题的第一部分,您有以下选择,

对于问题的第二部分 - 关于从数组中过滤零值 - 尝试:

my_array = my_array[my_array != 0]

my_array != 0 创建一个由 TrueFalse 组成的逻辑数组,然后在切片中使用。但是,这会返回一个您可能不想要的一维数组。要将值设置为其他值(并保持 2D 形状),请使用以下内容(值设置为 NaN)...

my_array[my_array != 0] = np.NaN

关于python - 对数二维 - 使用 matplotlib 的直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6966358/

相关文章:

python - 我想使用 Networkx 和 Matplotlib 输出 3D 图形

python - 获取 Sentry 的事件页面 url

python - 在 csv 文件中添加填充以使数据框可供 pandas 读取

python - 对包含表示 Pandas 中软件版本的字符串的列进行排序

python - 避免 NaN 值并在 python 中明智地添加两个矩阵元素

python - 如何使用 matplotlib 在单个页面上制作多个图?

python - 在 PyRoot 中声明一个 TTree 分支

python - 定心矩阵

python - 如何仅替换 numpy 数组中大于某个值的前 n 个元素?

python - 运行时错误 : The current Numpy installation fails to pass a sanity check due to a bug in the windows runtime