Skip to content

Instantly share code, notes, and snippets.

@se4u
Last active May 10, 2018 20:23
Show Gist options
  • Save se4u/e1eb98805ff307bd33fe2b201353288d to your computer and use it in GitHub Desktop.
Save se4u/e1eb98805ff307bd33fe2b201353288d to your computer and use it in GitHub Desktop.
Wolframalpha replacement for automatic interactive plots from the terminal
#!/usr/bin/env python
import sys
from pdb import set_trace
import sympy as ss
from mpmath import *
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
import argparse
from sympy.abc import x,y
arg_parser = argparse.ArgumentParser(description='''
# USAGE:
./plot "x - 1/x" -10.05 10 0.1
./plot "mp.e**(x) - 1/(mp.e**(x))" -10.05 10 0.1
''')
arg_parser.add_argument('expr')
arg_parser.add_argument('start', default=0., type=float, nargs='?')
arg_parser.add_argument('stop', default=1., type=float, nargs='?')
arg_parser.add_argument('step', default=0.1, type=float, nargs='?')
arg_parser.add_argument('starty', default=0., type=float, nargs='?')
arg_parser.add_argument('stopy', default=1., type=float, nargs='?')
arg_parser.add_argument('stepy', default=0.1, type=float, nargs='?')
arg_parser.add_argument('--plot', default='plt.plot', type=str, help='plt.semilogx | plt.plot')
args=arg_parser.parse_args()
expr, start, stop, step, starty, stopy, stepy = args.expr, args.start, args.stop, args.step, args.starty, args.stopy, args.stepy
f = eval(expr)
xv = np.arange(start, stop, step)
yv = np.arange(starty, stopy, stepy)
def reshape(arr):
return np.reshape(np.array(arr), (len(xv), len(yv)))
if f.free_symbols == set([x]):
fv = [f.subs(x, v).evalf() for v in xv]
eval(args.plot)(xv, fv)
npf = lambda x: np.array(x, dtype=float)
plt.ylim(npf(max(-100, min(fv))), npf(min(100, max(fv))))
plt.grid(True)
else:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y = np.meshgrid(xv, yv)
Z = reshape([float(f.subs(x, _x).subs(y, _y)) for _x in xv for _y in yv])
surf = ax.plot_surface(X, Y, Z, alpha=0.5, antialiased=False, cmap=cm.coolwarm) #
cset = ax.contour(X, Y, Z, cmap=cm.coolwarm)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title(expr)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment