pythonnumpyplotgradient

Calculate and plot gradient for every Nth value in array


Is it possible to use np.gradient to calculate the gradient of every 10th value in a given array?

rand = np.random.randint(low=1, high=10, size=(100,))

NOTE: I would like to calculate the gradient twice. Once between every value and once between every 10th value. I would then like to plot both. The 10 values should appear at every tenth position. This is why I can't seem to extract the values at the beginning.


Solution

  • Calculate gradiebt between every value first

    import numpy as np
    import matplotlib.pyplot as plt
    
    rand = np.random.randint(low=1, high=10, size=(100,))
    gradient_full = np.gradient(rand)
    

    Calculate gradient between every 10th value

    rand_10th = rand[::10]
    gradient_10th = np.gradient(rand_10th)
    

    create plot

    x_full = np.arange(100)
    x_10th = np.arange(0, 100, 10)
    

    Plot

    plt.figure(figsize=(12, 6))
    
    plt.plot(x_full, gradient_full, label='Gradient (every value)', alpha=0.7)
    plt.plot(x_10th, gradient_10th, 'ro-', label='Gradient (every 10th value)', markersize=8)
    
    plt.xlabel('Index')
    plt.ylabel('Gradient')
    plt.title('Comparison of Gradients')
    plt.legend()
    plt.grid(True)
    
    plt.show()
    

    output enter image description here