为什么水平线仅部分显示在sage / matplotlib中?

问题描述 投票:1回答:2

我有以下sage代码生成函数的matplotlib图:

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

我还希望在a = 4.0001时绘制点(a, f(a)),并从y轴到此点绘制红色虚线。这是我写的代码:

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)

但是,这会输出下图,水平线仅部分显示(它不与点pt相交):

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

为什么这条水平线仅部分显示?

我需要做些什么来正确绘制常数函数y = f(4.0001)的线?

python matplotlib plot graph sage
2个回答
1
投票

使用matplotlib的hlines函数可能更好,你只需要指定y值和xminxmax,即

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()

哪个会给你

HLine with function


请注意,在整个示例中直接使用matplotlib进行了一些调整 - 它们并不重要。


1
投票

Sage允许用户在绘图时指定x值的范围。

如果没有任何指示,它将从-1到1进行绘图。

在绘制f值为-1到5的x值之后:

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

为什么不将常数f(a)也从-1到5绘制:

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

从(0,f(a))到(a,f(a))的线也可以简单地绘制为:

L = line([(0, f(a)), (a, f(a))], color='red', linestyle='--')
© www.soinside.com 2019 - 2024. All rights reserved.