# Line Plot with Marked Optima

Next, let’s draw the line plot again and this time draw a point where the known optima of the function is located.

This can be helpful when studying an optimization algorithm as we might want to see how close an optimization algorithm can get to the optima.

First, we must define the input for the optima, then evaluate that point to give the x-axis and y-axis values for plotting.

# define the known function optima

optima_x = 0.0
optima_y = objective(optima_x)
We can then plot this point with any shape or color we like, in this case, a red square.

# draw the function optima as a red square

pyplot.plot([optima_x], [optima_y], ‘s’, color=‘r’)
Tying this together, the complete example of creating a line plot of the function with the optima highlighted by a point is listed below.

# line plot of input vs result for a 1d objective function and show optima

from numpy import arange
from matplotlib import pyplot

# objective function

def objective(x):
return x**2.0

# define range for input

r_min, r_max = -5.0, 5.0

# sample input range uniformly at 0.1 increments

inputs = arange(r_min, r_max, 0.1)

# compute targets

results = objective(inputs)

# create a line plot of input vs result

pyplot.plot(inputs, results)

# define the known function optima

optima_x = 0.0
optima_y = objective(optima_x)

# draw the function optima as a red square

pyplot.plot([optima_x], [optima_y], ‘s’, color=‘r’)

# show the plot

pyplot.show()
Running the example creates the familiar line plot of the function, and this time, the optima of the function, e.g. the input that results in the minimum output of the function, is marked with a red square.

This is a very simple function and the red square for the optima is easy to see.

Sometimes the function might be more complex, with lots of hills and valleys, and we might want to make the optima more visible.

In this case, we can draw a vertical line across the whole plot.

# draw a vertical line at the optimal input

pyplot.axvline(x=optima_x, ls=’–’, color=‘red’)
Tying this together, the complete example is listed below.

# line plot of input vs result for a 1d objective function and show optima as line

from numpy import arange
from matplotlib import pyplot

# objective function

def objective(x):
return x**2.0

# define range for input

r_min, r_max = -5.0, 5.0

# sample input range uniformly at 0.1 increments

inputs = arange(r_min, r_max, 0.1)

# compute targets

results = objective(inputs)

# create a line plot of input vs result

pyplot.plot(inputs, results)

optima_x = 0.0

# draw a vertical line at the optimal input

pyplot.axvline(x=optima_x, ls=’–’, color=‘red’)

# show the plot

pyplot.show()
Running the example creates the same plot and this time draws a red line clearly marking the point in the input space that marks the optima.