J. Taylor
J. Taylor

Reputation: 4865

Sage: How to plot points along the graph of a function f(x) at specific values of x?

If I have a 2-D plot of a function f(x), like this:

f(x) = sin(x)
show(plot(f, (x,0, 2 * pi)))

Using Sage, how do I draw points along the graph of f(x) at specified values of x? For example, how would I display red dots on top of the graph above so that it looks like the graph below?

graph of sine function with red dots at specific points on graph

Given a list of values L= [0, pi/8, pi/4, pi/2, 3*pi/4, pi], is there a concise way to draw points on the graph of f(x) at each of these values of x?

Upvotes: 1

Views: 2427

Answers (1)

Samuel Lelièvre
Samuel Lelièvre

Reputation: 3453

To plot a list of points, use points or point2d. See:

Note that you can also customize the ticks on the axes to match the points you are plotting.

Here is an example.

sage: f(x) = sin(x)
sage: xx = [0, pi/8, pi/4, pi/2, 3*pi/4, pi]
sage: yy = [f(x) for x in xx]
sage: xy = list(zip(xx, yy))
sage: f_plot = plot(f, (x, 0, 2*pi), ticks=(xx, yy), tick_formatter=(pi, None))
sage: f_dots = points(xy, color='red')
sage: p = f_plot + f_dots
sage: p

Save the plot using p.save:

sage: p.save('plot_sin_with_points.png')

Plot sine curve with some points

To make the points larger, use size (the default size is 10).

To set the order of layers of the graphic elements in a sum, use zorder.

For example one could define f_dots as follows instead of the above:

sage: f_dots = points(xy, color='red', size=30, zorder=20)

and get larger red dots, sitting "on top" of the curve instead of "underneath".

Upvotes: 2

Related Questions