Retrieve the PPSD.plot 2d histogram using obspy

I am using the ObsPy Python library and I want to plot the PPSD but without using the PPSD.plot() function of ObsPy, because I look for using some matplotlib utilities which are not implemented in the obspy.signal.spectral_estimation.PPSD class (see ObsPy doc).

For simplicity, first, I try to create this kind of figure:

ppsd.plot()

The best thing I managed to do is by using the ppsd.current_histogram.T*100/(ppsd.current_histogram_count) to get the probability of ppsd.

Here’s the function I implemented:

from obspy.signal.spectral_estimation import get_nlnm, get_nhnm
from obspy.signal import PPSD
import matplotlib.pyplot as plt
from obspy.imaging.cm import pqlx
import numpy as np
plt.close("all")

file = "CCN_301_DNZ_ppsd.npz" # <= .npz file with the stored ppsd
ppsd = PPSD.load_npz(file)

freq = False

def plot_ppsd_data(ppsd, xaxis_frequency = False, show_percentiles = True, show_mean = True, show_model = True):
    
    """
    
    Manual plot of the ppsd data from obspy library between 0.01 (s or Hz) and 100 (s or Hz)
    The function offers the option to plot the noise models from (Peterson, 1993) 
    and basic statistics.
    
    Parameters
    -----------
    ppsd: obspy class => can be obtained using:
       from obspy.signal import PPSD 
       PPSD.load_npz(file)
    xaxis_frequency: bol, default = False
        if True, shows the plot in frequency domain
    show_percentiles: bol, default = True
        if True, shows the percentiles of the ppsd curves
    show_mean: bol, default = True
        if True, shows the mean of the ppsd curves
    show_model: bol, default = True
        if True, shows the high and low new ambient noise models from (Peterson, 1993) 
    
    Returns
    ----------
    None
    
    """
    
    # Read the start and end date of the PPSD
    start_date = ppsd.times_processed[0].date
    end_date = ppsd.times_processed[-1].date
    start_date_string = start_date.strftime("%Y-%m-%d")
    end_date_string = start_date.strftime("%Y-%m-%d")
    
    # PLOT-----------------------
    plt.figure(figsize = (14,8))
    plt.title(ppsd.station + "." + ppsd.channel + "." + start_date_string + "--" + end_date_string)
    ax = plt.subplot()
    
    # Set logarithmic x axis
    x = np.logspace(np.log10(ppsd.psd_periods[0]), np.log10(ppsd.psd_periods[-1]), ppsd.current_histogram.shape[0])
    y = np.linspace(-200, - 50, 150)
    
    ppsd_2d = ppsd.current_histogram.T*100/(ppsd.current_histogram_count)
    # Statistics
    curves = np.array(ppsd.psd_values)
    percentiles = np.percentile(curves, q=[1, 95], axis=0)
    # Import the NLNM and NHNM
    nlnm_periods, nlnm = get_nlnm()
    nhnm_periods, nhnm = get_nhnm()
    
    X, Y = np.meshgrid(x, y)
    plt.pcolor(X,Y, ppsd_2d,  cmap = pqlx, vmax = 30)
    
    plt.xscale("log")
    plt.grid(True, which='both')
    # Labels
    plt.xlabel("Period [s]")
    plt.ylabel("Amplitude [m2/s4/Hz][dB]")
    cbar = plt.colorbar(ax=ax)
    cbar.set_label("[%]")
    
    
    labels = [None, 0.01, 0.1, 1, 10, 100]
    ax.set_xticklabels(labels)
    plt.xlim(0.01, 500)
    plt.ylim(-200, -50)
    
    # Options------------
    if show_model:
        plt.plot(nlnm_periods, nlnm, c = "grey", linewidth = 3)
        plt.plot(nhnm_periods, nhnm, c = "grey", linewidth = 3)
    
    if show_percentiles:
        plt.plot(x, percentiles[0], c = "k", linewidth = 2)
        plt.plot(x, percentiles[1], c = "k", linewidth = 2)
    if show_mean:
        plt.plot(x, np.mean(curves, axis = 0), c = "k", linewidth = 2)
    
    if xaxis_frequency:
        plt.xlabel("Frequency [Hz]")
        ax.set_xlim(right=100)
        # Flip the x-axis
        ax.invert_xaxis()

        # Maintain the same x tick labels and format
        # Get the current x-axis tick labels and format
        xticklabels = ax.get_xticklabels()[::-1]
        # Set the flipped x-axis tick labels and format
        #ax.set_xticks(xticks)
        ax.set_xticklabels(xticklabels)
        
        # Maintain the same x limits
        xlim = ax.get_xlim()
        ax.set_xlim(xlim)
        
        plt.show()
    

if __name__ == "__main__":
    plot_ppsd_data(ppsd, xaxis_frequency= freq) 

This gives me nearly the same result as ppsd.plot():

my_code_ppsd

But I have the impression that this is a pretty ugly method. Can anyone tell me if there are any better options, please?

New contributor

Geostrophy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật