0

I have a Sympy function, a sequence of x coordinates and a graph drawn using "plot".

import numpy as np
import sympy as sp

x = sp.Symbol('x')
xs = np.linspace(-2, 3, 5) #[-2.   -0.75  0.5   1.75  3.  ]
ys = sp.cos(2*x)*(sp.sin(2*x) + 1.5)+sp.cos(x)
graph = sp.plot(ys, xlim=[-2,3])

How could I draw markers on the function at X coordinates from xs variable?

The graph I get: Graph

The graph I would like to get: Prefered graph

  • 1
    To get the corresponding y-coordinates: `[ys.subs(x, xi).evalf() for xi in xs]` – JohanC Nov 26 '21 at 19:47
  • 1
    See [How To Graph Points With Sympy?](https://stackoverflow.com/questions/53289609/how-to-graph-points-with-sympy) – JohanC Nov 26 '21 at 19:58

1 Answers1

1

Sympy's plot supports a markers= keyword. This is a list of dictionaries towards matplotlib's plot. Sympy's subs can be used to fill in an x value into the formula.

import numpy as np
import sympy as sp

x = sp.Symbol('x')
y = sp.Symbol('y')
ys = sp.cos(2 * x) * (sp.sin(2 * x) + 1.5) + sp.cos(x)

xs = np.linspace(-2, 3, 5)  # [-2.   -0.75  0.5   1.75  3.  ]
yvals = [ys.subs(x, xi) for xi in xs]

plot = sp.plot(ys, xlim=[-2.2, 3.2],
               markers=[{'args': [xs, yvals, 'ro']}])

sympy plot with markers

JohanC
  • 71,591
  • 8
  • 33
  • 66