Wednesday, July 3, 2024

Python Simple Graphing (part 2)

With the little program from my previous post, I thought I could graph any function I passed to it? Let me try something a little more fancy like sin(x). I tried the following and got error
import matplotlib.pyplot as plt
import numpy as np
import math


def f(x):
    return math.sin(x)

# using 101 steps so I know I get to 0
x = np.linspace(-5,5,101)

plt.plot(x,f(x))
plt.show()
Error is "TypeError: only length-1 arrays can be converted to Python scalars". What??

Oh that's because this plt.plot() method really takes 2 arrays, the x values and the y values.

The following works better

import matplotlib.pyplot as plt
import numpy as np
import math


def f(x):
    return math.sin(x)

# using 101 steps so I know I get to 0
x = np.linspace(-5,5,101)

yv = np.zeros(len(x))
for i in range(len(x)):
    yv[i] = f(x[i])

plt.plot(x,yv)

plt.show()
This works a little better but I like axes and grids and properly scaled graph!

Ok after a little researching here we go:

import matplotlib.pyplot as plt
import numpy as np
import math

XMIN, XMAX = -5, 5
YMIN, YMAX = -5, 5
GRIDSIZE = 1

STEPS = 101


def f(x):
    return math.sin(x)


# using odd steps so I know I get to 0
x = np.linspace(XMIN,XMAX,STEPS)
plt.axis([XMIN,XMAX,YMIN,YMAX]) 

plt.title('my graph')

yv = np.zeros(len(x))
for i in range(len(x)):
    yv[i] = f(x[i])

plt.plot(x,yv)

# make axes
plt.axhline(y=0, color='k') # 'k' means black
plt.axvline(x=0, color='k')
# gca is get current axes 
plt.gca().set_aspect('equal')
plt.gca().set_xticks(np.arange(XMIN,XMAX,GRIDSIZE))
plt.gca().set_yticks(np.arange(YMIN,YMAX,GRIDSIZE))
plt.grid(True)

plt.show()

No comments: