Skip to content

Instantly share code, notes, and snippets.

@jsbueno
Created May 16, 2019 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsbueno/577ce78ae12f07f83e0fd9b548bd2b18 to your computer and use it in GitHub Desktop.
Save jsbueno/577ce78ae12f07f83e0fd9b548bd2b18 to your computer and use it in GitHub Desktop.
matplotlib - plot programatic function without explictly generating all Y points into a ndarray
class YRenderer:
def __init__(self, x, func):
self.x = x
self.func = func
def __len__(self):
return len(self.x)
def __getitem__(self, index):
return self.func(self.x[index])
import numpy as np
from matplotlib import pyplot as plt
import math
# This simple example still requires X points in an ndarray, old-style:
x = np.arange(0, 10, .1)
# but for y data, we can use the class in the snippet above:
# replace math.sin for any function you want.
# Not that a scalar function is used, not one that operates on ndarrays (so, not np.sin)
y = YRenderer(x, math.sin)
plt(x, y)
plt.plot(x, y)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment