Search code examples
pythonmatplotlibplotmath.sqrt

Square root plot in matplotlib in python


How to make sqrt(x) function plot in matplotlib in python?

I tried writing y = sqrt(x) but it gave an TypeError: only size-1 arrays can be converted to Python scalars. I have never had experience with matplotlib before, therefore I would be glad to get some advice.


Solution

  • Here comes a small example:

    import matplotlib.pyplot as plt
    import math
    # print y = math.sqrt(x)
    
    # calculate the points x, y
    x = [0, 0.3, 0.5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 25, 36, 49]
    y = [math.sqrt(y) for y in x]
         
    fig, ax = plt.subplots()
    ax.plot(x, y)
     
    ax.set(xlabel='value', ylabel='sqrt', title='Square root of list values')
        
    ax.grid()
    fig.savefig("sqrt.png")
    
    plt.show()
    

    Output:

    [![sqrt][1]][1]