from __future__ import print_function from os import path import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator, FormatStrFormatter ImgsPath = r'C:\CJS\prj\Python\ws\charts\imgs' fn = 'sines-2.png' tex = r'$\frac{x^1}{1!} - \frac{x^3}{3!} + \frac{x^5}{5!} - \frac{x^7}{7!} + ...$' Factorial = lambda n: n if n<=2 else (n * Factorial(n-1)) Taylor = lambda x,n: ((x**n) / Factorial(n)) x0, x1 = -3.00, +3.00 y0, y1 = -2.50, +2.50 xmin, xmax = (x0 * np.pi), (x1 * np.pi) xt = np.linspace(x0, x1, 7) xx = np.linspace(xmin, xmax, 201) dx1 = [+Taylor(x, 1) for x in xx] dx2 = [-Taylor(x, 3) for x in xx] dx3 = [+Taylor(x, 5) for x in xx] dx4 = [-Taylor(x, 7) for x in xx] dx5 = [+Taylor(x, 9) for x in xx] dx6 = [-Taylor(x,11) for x in xx] dx7 = [+Taylor(x,13) for x in xx] dx8 = [-Taylor(x,15) for x in xx] dx9 = [+Taylor(x,17) for x in xx] dx0 = [sum(t) for t in zip(dx1,dx2,dx3,dx4,dx5,dx6,dx7,dx8,dx9)] sx0 = [np.sin(x) for x in xx] fig, ax = plt.subplots() fig.suptitle('Taylor Series for Sine (1,3,5,..17)') ax.set_xlim(xmin, xmax) ax.set_ylim(y0, y1) ax.minorticks_on() ax.set_xticks([x*np.pi for x in xt]) ax.set_xticklabels(['%+d $pi$' % int(x) for x in xt]) ax.xaxis.set_minor_locator(MultipleLocator(np.pi/4)) ax.yaxis.set_major_locator(MultipleLocator(1.00)) ax.yaxis.set_minor_locator(MultipleLocator(0.25)) ax.yaxis.set_major_formatter(FormatStrFormatter('%+.2f')) ax.tick_params(which='major', axis='both', direction='out', zorder=0) ax.tick_params(which='minor', axis='both', direction='out', zorder=0) ax.grid(which='minor', axis='both', color='#efefff', lw=0.6,ls='-',zorder=0, alpha=1.0) ax.grid(which='major', axis='both', color='#7f7fbf', lw=1.2,ls='-',zorder=2, alpha=1.0) ax.axhline(0.0, color='k', lw=1.8, zorder=5) ax.axvline(0.0, color='k', lw=1.8, zorder=5) ax.plot(xx,dx1, color='#000000', lw=0.80, zorder=4, alpha=1.00) ax.plot(xx,dx2, color='#1f1f1f', lw=0.80, zorder=4, alpha=1.00) ax.plot(xx,dx3, color='#3f3f3f', lw=0.80, zorder=4, alpha=1.00) ax.plot(xx,dx4, color='#5f5f5f', lw=0.80, zorder=4, alpha=1.00) ax.plot(xx,dx5, color='#7f7f7f', lw=0.80, zorder=4, alpha=1.00) ax.plot(xx,dx6, color='#9f9f9f', lw=0.80, zorder=4, alpha=1.00) ax.plot(xx,dx7, color='#afafaf', lw=0.80, zorder=4, alpha=1.00) ax.plot(xx,dx8, color='#cfcfcf', lw=0.80, zorder=4, alpha=1.00) ax.plot(xx,dx9, color='#dfdfdf', lw=0.80, zorder=4, alpha=1.00) p1 = ax.plot(xx,dx0, color='#ff0000', lw=1.60, zorder=8, alpha=1.00) p2 = ax.plot(xx,sx0, color='#0000ff', lw=1.20, zorder=9, alpha=0.50) ax.legend([p1[0],p2[0]],[tex,'sin(x)'], loc='upper left', shadow=True) fig.set_figwidth(8.0) fig.set_figheight(4.8) fig.subplots_adjust(left=0.08, bottom=0.10, right=0.97, top=0.90) fig.savefig(path.join(ImgsPath,fn)) #plt.show()