Square root plot in matplotlib in python

234 Views Asked by At

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.

2

There are 2 best solutions below

2
Hermann12 On BEST ANSWER

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]
1
Naitzirch On

It looks like you're using math.sqrt to convert the x array to it's square root.
Instead use np.sqrt, this will return a numpy array.

>>> import numpy as np
>>> x = np.array([4, 9, 16])
>>> y = np.sqrt(x)
>>> y
array([2., 3., 4.])
>>>
>>> math.sqrt(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: only size-1 arrays can be converted to Python scalars
>>>

It's an error that happens when you try to pass an array to a function that only accepts 1 parameter. np.int(y) would yield the same error for example.