[Python] How to plot a Probability Density Function in Python?

Discussão em 'Python' iniciado por Stack, Janeiro 22, 2025.

  1. Stack

    Stack Membro Participativo

    I want to plot a Probability Density Function for the offsets from a log file. Here is the code:

    timestamps = []
    sequences = []

    log_Name = 'test_rtt_25-01-17_13-07-41_values5_rate50.log'
    log_Path = "/home/ubuntu/results-25-01-09-docker/"
    true_Path = log_Path + log_Name
    with open(true_Path, "r") as f:
    for line in f:
    if not line.startswith('#'):
    time_part, seq_part = line.strip().split('(')
    base, offset = time_part.split('+')

    timestamps.append(float(offset))

    seq = int(seq_part[:-1])
    sequences.append(seq)


    The code upon reads the data from the log file and then saves the offsets and sequences in 'timestamps' and 'sequences'.

    Here is an example for 'timestamps' and 'sequences'.

    [0.001009023, 0.001055868, 0.000992934, 0.001148472, 0.001086814, 0.001110649, 0.001066759, 0.00126167, 0.001231778, 0.000944345]

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


    As you can see there are 10 offsets and 10 sequences. Each offset has its number, for example: 0.001009023 is number 1. I want to plot a Probability Density Function, and i tried this:

    source = {'seqs': sequences, 'times': timestamps}
    df = pd.DataFrame(source)
    df.sort_values(by = ['times'], inplace=True)
    df_mean = np.mean(df['times'])
    df_std = np.std(df['times'])
    pdf = stats.norm.pdf(df['times'], df_mean, df_std)
    plt.plot(df['times'], pdf)
    plt.xlabel('Offsets') # Label for the x-axis
    plt.savefig('/home/ubuntu/')


    But the output y-axis is really strange, it looks like this: [​IMG]

    Working complete code with input and imports:

    import pandas as pd

    import numpy as np

    import matplotlib.pyplot as plt

    import scipy.stats as stats

    timestamps = [0.001009023, 0.001055868, 0.000992934, 0.001148472, 0.001086814, 0.001110649, 0.001066759, 0.00126167, 0.001231778, 0.000944345]

    sequences = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    source = {'seqs': sequences, 'times': timestamps}

    df = pd.DataFrame(source)

    df.sort_values(by = ['times'], inplace=True)

    df_mean = np.mean(df['times'])

    df_std = np.std(df['times'])

    pdf = stats.norm.pdf(df['times'], df_mean, df_std)

    plt.plot(df['times'], pdf)

    plt.xlabel('Offsets') # Label for the x-axis

    plt.savefig('fig.png')

    plt.show()


    Output:

    [​IMG]

    I have no idea why the probability is much bigger than 1, it should be smaller than 1. Anyone knows where i did wrong?

    Continue reading...

Compartilhe esta Página