DDC-10: Annotate the minimum
A data challenge a day helps you master machine learning
About these daily data challenges
Each post is an exercise that helps you learn about data in Python.
Try to solve the exercise before checking my solution at the bottom of the post 🤓
You can share your solution or visualization in the comments!
Today’s challenge
Write code to reproduce the figure below. Use the annotation()
method on a matplotlib axis to show the text and wedge. The formula that defines the values is printed on the y-axis.
.
.
.
.
Scroll down for the solution…
.
.
.
.
.
.
.
.
keep scrolling!
.
.
.
.
# the function
x = np.arange(-5,5.1,.5)
y = x**2 + np.cos(x)*10
# the minimum
minpnt = np.argmin(y)
# the plot
fig,ax = plt.subplots(1,figsize=(8,5))
ax.plot(x,y,'ko-',markerfacecolor=[.9,.7,.9],markersize=10)
ax.annotate(f'min: ({x[minpnt]:.2f},{y[minpnt]:.2f})',(x[minpnt],y[minpnt]),
arrowprops = dict(color=[.7,.7,.9],arrowstyle='wedge'),
xycoords = 'data',
xytext = (x[int(len(x)/2)],np.max(y)*.8),horizontalalignment='center',
fontsize = 14)
ax.set_xlabel('x')
ax.set_ylabel(r'$f(x) = x^2 + 10\;\cos(x)$',fontsize=15)
plt.show()