使用matplotlib的对数二维直方图

2024-10-01 09:26:32 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我用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()

Tags: inimportfornpaxwherematrixmax
1条回答
网友
1楼 · 发布于 2024-10-01 09:26:32

对于问题的第一部分,你有以下几种选择:

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

my_array = my_array[my_array != 0]

my_array != 0创建一个True和{}的逻辑数组,然后在片中使用。但是,这将返回一个您可能不需要的一维数组。要将值设置为其他值(并保持2D形状),请使用以下命令(值设置为NaN)。。。在

my_array[my_array != 0] = np.NaN

相关问题 更多 >