J. Taylor
J. Taylor

Reputation: 4865

Why is horizontal line only partially displayed in sage / matplotlib?

I have the following sage code that generates a matplotlib graph of the function:

stupid that I can't use LATEX on this site and have to upload a gif :(

I additionally wish to plot the point (a, f(a)) when a = 4.0001, and a dashed red line from the y-axis through this point. Here is the code that I wrote to do this:

f(x) = (x**2 - 2*x - 8)/(x - 4)
g = plot(f, x, -1, 5)

a = 4.0001  
L = plot(f(a), color='red', linestyle="--")
pt = point((a, f(a)), pointsize=25)

g += pt + L
g.show(xmin=0, ymin=0)

However, this outputs the following graph with the horizontal line only partially displayed (it does not intersect the point pt):

graph of function f(x) = (x**2 - 2*x - 8)/(x - 4)

Why is this horizontal line only partially displayed?

What do I need to do to correctly graph the line of constant function y = f(4.0001)?

Upvotes: 1

Views: 596

Answers (2)

Samuel Lelièvre
Samuel Lelièvre

Reputation: 3453

Sage lets the user specify the range of x values when plotting.

Failing any indication, it will plot from -1 to 1.

After plotting f for x-values from -1 to 5:

g = plot(f, x, -1, 5)

why not plot the constant f(a) also from -1 to 5:

L = plot(f(a), x, -1, 5, color='red', linestyle="--")

A line from (0, f(a)) to (a, f(a)) can also be plotted simply as:

L = line([(0, f(a)), (a, f(a))], color='red', linestyle='--')

Upvotes: 1

William Miller
William Miller

Reputation: 10330

It is probably better to use matplotlib's hlines function, for which you simply need to specify the y-value and the xmin and xmax, i.e.

import matplotlib.pyplot as plt
import numpy as np

def f(x):
    return (x**2 - 2*x - 8)/(x - 4)

x = np.linspace(-5,5, 100)
a = 4.001

plt.plot(x, f(x), -1, 5, linestyle='-')
plt.hlines(6, min(x), max(x), color='red', linestyle="--", linewidth=1)
plt.scatter(a, f(a))
plt.xlim([0, plt.xlim()[1]])
plt.ylim([0, plt.ylim()[1]])
plt.show()

Which will give you

HLine with function


Note that some adjustments were made to use matplotlib directly throughout the example - they are not critical.

Upvotes: 1

Related Questions