我在这里进行一些数学优化,我想知道如何使用matplotlib在绘图图中标记某个点或点列表(在我的情况下是局部最小值和最大值)。 这是代码:
# Import libraries
% matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
# (x, y) coordinates
x = np.linspace(-5, 3, 50)
y = (x**3 + 3*x**2 - 6*x - 8)/4
# Tangent line
def f(a):
return (a**3 + 3*a**2 - 6*a - 8)/4
def df(a):
return 3/2 * ((1/2)*a**2 + a - 1)
def tangent(x, a):
return f(a) + df(a) * (x - a)
# plotting the cubic function
# plotting a vertical line passing through the local maxima
# plotting a vertical line passing through the local minima
plt.plot(x, y)
plt.axvline(x = - np.sqrt(3) - 1, color = 'r', linestyle = '--')
plt.axvline(x = np.sqrt(3) - 1, color = 'r', linestyle = '--')
plt.plot(x[0:30], tangent(x[0:30], - np.sqrt(3) - 1), 'r')
plt.plot(x[20:50], tangent(x[20:50], np.sqrt(3) - 1), 'r')
plt.title("Local minima and maxima of a cubic function")
plt.xlabel("x")
plt.ylabel("y")
如您所见,当我只想要两个点来指定绘制图形的局部最小值和最大值时,有两条切线和两条垂直线穿过三次方函数的局部最小值和局部最大值。