Search code examples
pythonnumpymathmatplotliblogarithm

Plotting the logarithm of a function


I have a function which I am able to plot. Now I would like to plot the logarithm of this function. Python says that log10() is not defined for functions (and I understand that). So the question is: how can I plot the logarithm of a function like f(x,a)=a*(x**2)?


Solution

  • It is misleading to say that matplotlib can plot functions. Matplotlib can only plot values.

    So if your function is

    f = lambda x,a : a * x**2
    

    you'd first need to create an array of values for x and define a

    a=3.1
    x = np.linspace(-6,6)
    

    You can then plot the array y = f(x,a) via

    ax.plot(x,y)
    

    If you now want to plot the logarithm of f, what you need to really do is plot the logarithm of your array y. So you'd create a new array

    y2 = np.log10(y)
    

    and plot it

    ax.plot(x,y2)
    

    In some cases, instead of showing the logarithm of a function on a linear scale, it may be better to show the function itself on a logarithmic scale. This can be done by setting the axes in matplotlib to logarithmic and plot the initial array y on that logarithmic scale.

    ax.set_yscale("log", nonposy='clip')
    ax.plot(x,y)
    

    So here is a showcase example of all three cases:

    import matplotlib.pyplot as plt
    import numpy as np
    
    #define the function
    f = lambda x,a : a * x**2
    
    #set values
    a=3.1
    x = np.linspace(-6,6)
    
    #calculate the values of the function at the given points
    y =  f(x,a)
    y2 = np.log10(y)
    # y and y2 are now arrays which we can plot
    
    #plot the resulting arrays
    fig, ax = plt.subplots(1,3, figsize=(10,3))
    
    ax[0].set_title("plot y = f(x,a)")
    ax[0].plot(x,y) # .. "plot f"
    
    ax[1].set_title("plot np.log10(y)")
    ax[1].plot(x,y2) # .. "plot logarithm of f"
    
    ax[2].set_title("plot y on log scale")
    ax[2].set_yscale("log", nonposy='clip')
    ax[2].plot(x,y) # .. "plot f on logarithmic scale"
    
    plt.show()
    

    enter image description here