You can influence the location LaTeX chooses to place an image using so-called placement specifiers, which are options provided to the figure environment. The following code fragment uses [h!], which instructs LaTeX to try to place the figure exactly where it appears in the text instead of letting it 'float' to another location in the document.
\begin{figure}[h!]

Despite using [h!] LaTeX might not be able to place the figure exactly where it was encountered. For more information on figure placement, see the Overleaf article Positioning images and tables.