Search code examples
pythonplotvisualizationmin

How find the minimum point on the plotted line (xmin, ymin) add the minimum point?


i can't find min. How to add minimum point? Please help How find the minimum point on the plotted line (xmin, ymin) add the minimum point ?

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-5, 5, 100)
y = x*x - 2*x + 23

# Plot
plt.plot(x, y)

# Plot title
plt.title("\nQuadratic Function: y=x*x - 5*x + 23\n", fontsize=16, weight="bold", color = "red")


# Axis Labels
plt.xlabel("X", fontsize = 10, weight="bold", color="red")
plt.ylabel("Y", fontsize = 10, weight="bold", color="red")

# Add minimum point: To Do 


# Grid
plt.grid()

# Display plot
plt.show()

How to fix the code to work?

a = (y[np.argmin(y)])
b = (x[np.argmin(x)])
print(a,b)
plt.scatter(a, b, color="lightgreen", s=25)

Solution

  • You mixed up your coordinates for the function's minimum. You want to have minimum y value but the corresponding x value for that y. This corresonding x value is calculated by a = x[y.argmin()]. See code below:

    
    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(-5, 5, 100)
    y = x*x - 2*x + 23
    
    # Plot
    plt.plot(x, y)
    
    # Plot title
    plt.title("\nQuadratic Function: y=x*x - 5*x + 23\n", fontsize=16, weight="bold", color = "red")
    
    
    # Axis Labels
    plt.xlabel("X", fontsize = 10, weight="bold", color="red")
    plt.ylabel("Y", fontsize = 10, weight="bold", color="red")
    
    plt.grid()
    
    a = x[y.argmin()]
    b = y.min()
    plt.scatter(a, b, color="lightgreen", s=25)
    
    

    enter image description here