GitLab Repo

amachine.am_visualization.am_histogram

 1import matplotlib.pyplot as plt
 2import numpy as np
 3
 4def index_histogram(
 5    data, 
 6    output_path : str,
 7    title : str = "Index Frequency",
 8    x_label : str = "index",
 9    show : bool = False
10):
11    """
12    Plots a histogram for integer data where bins are 1 unit wide
13    and centered on the integers.
14    """
15    if len(data) == 0:
16        print("No data provided.")
17        return
18
19    data = np.array(data)
20    min_val = int(np.min(data))
21    max_val = int(np.max(data))
22
23    print( data.size )
24
25    # Count occurrences of each integer
26    counts = np.bincount(data)
27
28    print(counts.size )
29
30    # Generate the x-axis indices
31    indices = np.arange(len(counts))
32
33    fig, ax = plt.subplots(figsize=(12, 6))
34    
35    # Plot bars
36    # width=1.0 makes them touch, 0.8 adds a slight gap
37    ax.bar(indices, counts, width=1.0)
38
39    # Add Statistics
40    min_freq = np.min(counts)
41    max_freq = np.max(counts)
42    mean_freq = np.mean(counts)
43    stats_text = (f"Min Freq: {min_freq}\n"
44                  f"Max Freq: {max_freq}\n"
45                  f"Mean Freq: {mean_freq:.1f}")
46    
47    # Place text in the top-right corner using axis coordinates (0 to 1)
48    ax.text(0.98, 0.95, stats_text, transform=ax.transAxes, 
49            fontsize=12, verticalalignment='top', horizontalalignment='right',
50            bbox=dict(boxstyle='round', facecolor='white', alpha=0.8))
51
52    # Since 300 is a lot of ticks, we only show a subset to keep the axis readable
53    # Remove this limit if you want every single integer labeled
54    if (max_val - min_val) > 20:
55        plt.locator_params(axis='x', nbins=20)
56    else:
57        plt.xticks(range(min_val, max_val + 1))
58    
59    ax.set_title(title)
60    ax.set_xlabel("Integer Value")
61    ax.set_ylabel("Frequency")
62    ax.grid(axis='y', linestyle='--', alpha=0.5)
63
64    plt.savefig( output_path, dpi=300, bbox_inches="tight" )
65
66    if show :
67        plt.show()
def index_histogram( data, output_path: str, title: str = 'Index Frequency', x_label: str = 'index', show: bool = False):
 5def index_histogram(
 6    data, 
 7    output_path : str,
 8    title : str = "Index Frequency",
 9    x_label : str = "index",
10    show : bool = False
11):
12    """
13    Plots a histogram for integer data where bins are 1 unit wide
14    and centered on the integers.
15    """
16    if len(data) == 0:
17        print("No data provided.")
18        return
19
20    data = np.array(data)
21    min_val = int(np.min(data))
22    max_val = int(np.max(data))
23
24    print( data.size )
25
26    # Count occurrences of each integer
27    counts = np.bincount(data)
28
29    print(counts.size )
30
31    # Generate the x-axis indices
32    indices = np.arange(len(counts))
33
34    fig, ax = plt.subplots(figsize=(12, 6))
35    
36    # Plot bars
37    # width=1.0 makes them touch, 0.8 adds a slight gap
38    ax.bar(indices, counts, width=1.0)
39
40    # Add Statistics
41    min_freq = np.min(counts)
42    max_freq = np.max(counts)
43    mean_freq = np.mean(counts)
44    stats_text = (f"Min Freq: {min_freq}\n"
45                  f"Max Freq: {max_freq}\n"
46                  f"Mean Freq: {mean_freq:.1f}")
47    
48    # Place text in the top-right corner using axis coordinates (0 to 1)
49    ax.text(0.98, 0.95, stats_text, transform=ax.transAxes, 
50            fontsize=12, verticalalignment='top', horizontalalignment='right',
51            bbox=dict(boxstyle='round', facecolor='white', alpha=0.8))
52
53    # Since 300 is a lot of ticks, we only show a subset to keep the axis readable
54    # Remove this limit if you want every single integer labeled
55    if (max_val - min_val) > 20:
56        plt.locator_params(axis='x', nbins=20)
57    else:
58        plt.xticks(range(min_val, max_val + 1))
59    
60    ax.set_title(title)
61    ax.set_xlabel("Integer Value")
62    ax.set_ylabel("Frequency")
63    ax.grid(axis='y', linestyle='--', alpha=0.5)
64
65    plt.savefig( output_path, dpi=300, bbox_inches="tight" )
66
67    if show :
68        plt.show()

Plots a histogram for integer data where bins are 1 unit wide and centered on the integers.