from matplotlib.ticker import MaxNLocator
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import math
### x-values ###
xpt = 0
x_deviation = 10
x_increments = 21
xs_min = xpt - x_deviation
xs_max = xpt + x_deviation
xs = np.linspace(xs_min, xs_max, x_increments) # XS
### exclude x-values ### (eg f(x!=0)=1/x, f(x>0)=log(x))
# xs = xs[xs != 1]
xs = xs[xs > 0]
print(xs)
### the function ###
# lbl_fx = r'$f(x)= 6.1t^{2}-9.28t+16.43$' # LABEL
# lbl_fx = r'$f(x)= log(x)$' # LABEL
lbl_fx = r'$T=2\pi \sqrt{L}{g}$' # LABEL
# fx_fx = lambda x,L,g: 2 * math.pi * math.sqrt(L/g) # f(x)
fx_fx = lambda x: 2 * np.pi * np.sqrt(x/9.81) # f(x)
# fx_fx = lambda x: 2 * math.pi * x # f(x)
### y-values ###
ys_fx = fx_fx(xs) # ys=f(xs)
ypt_fx = fx_fx(xpt)
print(f"ypt_fx_at_P(x={xpt}): {ypt_fx}")
### fractions? ###
# lbl_denom = r'$f(x)=x-2$'
# fx_denom = lambda x: x-2
# ys_denom = fx_denom(xs)
### derivative ###
# lbl_dydx = r"$f'(x)=6.10*(2t)-9.28$ (dydx or slope fn)"
# lbl_dydx = lbl_fx
# fx_dydx = lambda x: 6.1*(2*x)-9.28
# xpt_dydx = xpt
# dydx = fx_dydx(xpt_dydx)
# print(f"ypt_dydx_at_P(x={xpt_dydx}): {dydx}")
### tangent ###
# c_tangent = ypt_fx-(dydx)*(xpt)
# tgt = "tangent"
# lbl_tangent = rf'$f_t(x)={dydx:,.1f}t+{c_tangent:,.1f}$ (tangent at x={xpt})'
# fx_tangent = lambda x: dydx*xs+c_tangent
# ys_tangent = fx_tangent(xs)
### plot things ####
plt.plot(xs, ys_fx, 'r^-', linewidth=2, markersize=6, label=lbl_fx)
# plt.scatter(xs, ys_fx, marker="o")
# plt.plot(xs, ys_tangent, 'yo-', linewidth=2, markersize=6, label=lbl_tangent)
# plt.plot(xs, ys_denom, 'bo-', linewidth=2, markersize=8, label=lbl_denom)
# plt.scatter(x=xpt, y=fx_fx(xpt), marker="o")
##### EXTRAS: title, grid, legend, zooming, ticks, hline, vline, tickers #####
# title
# plot_title = lbl_fx + f" & it's tangent at x={xpt}"
plot_title = lbl_fx
# plot_title = lbl_fx + "at (4,2)"
# plot_title = lbl_denom + " and " + lbl_denom + "at (3,3)"
# plot_title = lbl_fx + " and " + lbl_tangent + "at (4,2)"
plt.title(plot_title, loc='left')
# grid
plt.grid(color='lightgrey', linestyle='--', linewidth=0.5)
# legend plt.legend(loc='upper right')
plt.legend(loc='lower right')
# zoom! enhance! #
# plt.xlim(xpt-5,xpt+5) # x-rng
# plt.ylim(-0.1, 0.1) # y-rng
# vertical, horizontal,
# ax = plt.gca() # Get the current axis
# ax.axvline(x=xpt, color='grey', linestyle='--', linewidth=0.5)
# ax.axhline(y=fx_fx(xpt), color='grey', linestyle='--', linewidth=0.5)
# X-LIMIT & VALUE
# plt.vlines(x_at_c,linestyles="dotted", ymin=plt.ylim()[0], ymax=max(ys)) # non-monotonic
# plt.plot(x_at_c, 0.5,marker="o",markersize=15, markerfacecolor='none', markeredgecolor='red')
# OTHER
# b+-- , o:b , r^ , bo plt.xlabel("")
# plt.ylim(bottom=0) # chart starts from y=0
# ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.000025)) # minor ticks
# ref: https://matplotlib.org/stable/users/explain/axes/axes_ticks.html