Monday, June 10, 2024

Python simple graphing

Pyplot lets you easily make a graph: https://matplotlib.org/stable/tutorials/pyplot.html. Lots of options here.

You first need to install it:.

pip3 install matplotlib

Here is some simple code. x range from -5,5. plot y=x2+1

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5,5,0.1)
y = x*x+1
plt.plot(x,y)
plt.show()
Although this works but it seems wacky scale.

And let me try some other function, let's give it tricky function y=1/x: Eeew this is ugly (and wrong)

This can be fixed if I change x to x = np.linspace(-5,5,100). See documentation here: https://numpy.org/doc/stable/reference/generated/numpy.linspace.html

But eew, it is not what I expect it to do at x=0? First do a step with odd number so you know 0 gets evaluated, then make your function a little method, and have an extra with statement to ignore bad output

import matplotlib.pyplot as plt
import numpy as np

def f(x):
    with np.errstate(divide='ignore', invalid='ignore'):
        return 1/x

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

plt.plot(x,f(x))
plt.show()

Ok a few lines give you much functionality... but less than super smooth if you ask me... There are many ways to supply that x range. and many ways to tweak graph like add axes, colors, labels, etc.

No comments: