1

I'd like to plot a graph and highlight its local maximum by drawing a dotted line back to x and y axis, and displaying the values of both.

For example some data:

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import make_interp_spline

x_ = np.array([1, 2.5, 2.7, 8, 3])
y_ = np.array([1, 2, 3, 4, 5, 6])
spline = make_interp_spline(x_, y_)
x = np.linspace(x_.min(), x_.max(), 500)
y = spline(x)

xmax = x[np.argmax(y)]
ymax = y.max()
plt.plot(x, y)
plt.plot(xmax,ymax,'o')
plt.show()

How do I do this?

Thanks in advance

mozway
  • 194,879
  • 13
  • 39
  • 75
ellekalle
  • 43
  • 3
  • Your code doesn't really run... – Quang Hoang Nov 10 '21 at 14:35
  • 1
    Aside from the syntax errors I fixed, there are many issues, `x` should be sorted, and `y` should be of the same size – mozway Nov 10 '21 at 14:38
  • `.hlines` and `.vlines` will allow you to plot horizontal and vertical lines to a specific location. – Trenton McKinney Nov 10 '21 at 14:49
  • @Reti43, partly yes, but how do I then display the numerical value of my x and y values for the local maximum? – ellekalle Nov 10 '21 at 14:53
  • [Here](https://stackoverflow.com/questions/6282058/writing-numerical-values-on-the-plot-with-matplotlib). Welcome to the site and please take this as constructive criticism. A search is valuable and can save time. A question that seeks to combine independent things that have been asked before is of little value, unless the combination itself poses a new problem. – Reti43 Nov 10 '21 at 15:15

1 Answers1

1

The general code is OK, but there are two major mistakes:

1- x should be sorted

2- x and y should be of same size

Working version of the code:

import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import make_interp_spline

x_ = np.array([1, 2.5, 2.7, 3, 8])
y_ = np.array([1, 2, 3, 5, 4])
spline = make_interp_spline(sorted(x_), y_)
x = np.linspace(x_.min(), x_.max(), 500)
y = spline(x)

xmax = x[np.argmax(y)]
ymax = y.max()
plt.plot(x_, y_, 'o')
plt.plot(x, y)
plt.plot(xmax,ymax,'s')

# annotations
plt.axhline(ymax, ls=':', c='k')
plt.axvline(xmax, ls=':', c='k')
plt.text(xmax, ymax*0.95, f'({round(xmax,2)}, {round(ymax,2)})')

plt.show()

spline interpolation

mozway
  • 194,879
  • 13
  • 39
  • 75
  • 1
    The question asks to plot a line from the local maximum to the x and y axes, not to superimpose the original data points on the spline. – Reti43 Nov 10 '21 at 14:45
  • @Reti43 added, but the major issue was the fully broken code – mozway Nov 10 '21 at 14:48