我在 matplotlib 中绘制绝对值函数,图形只是围绕顶点
I'm plotting absolute value functions in matplotlib and the graph just goes around the vertex
我正在尝试绘制 f(X)= 2* abs(x-2)+4 的函数,但在顶点或点 (2,4) 处图形停止并绕过它。有什么办法可以改变它,让它真正达到目的吗?提前致谢。
import matplotlib.pyplot as plt
import numpy as np
import math
def graph(width, hight):
x = np.linspace(-width,width)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.set_ylim(-hight, hight)
ax.set_xlim(-width, width)
# the function
y = 2 * abs(x-2)+4
plt.plot(x,y,)
plt.xticks(np.arange(-width, width+1, 1.0))
plt.yticks(np.arange(-hight, hight+1, 1.0))
plt.grid(True)
plt.show()
graph(10, 10)
"""
您的目标问题是您使用 linspace
创建的范围。此方法的默认样本数为 50,它们会均匀分配,因此根据您的 width
,2
可能不在此范围内。使用 num
参数(第三个位置)增加此值,它看起来会更好,但您的值可能仍不在范围内。
(问题是你正在处理一个数字列表,你不能处理无限集)。
我正在尝试绘制 f(X)= 2* abs(x-2)+4 的函数,但在顶点或点 (2,4) 处图形停止并绕过它。有什么办法可以改变它,让它真正达到目的吗?提前致谢。
import matplotlib.pyplot as plt
import numpy as np
import math
def graph(width, hight):
x = np.linspace(-width,width)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.set_ylim(-hight, hight)
ax.set_xlim(-width, width)
# the function
y = 2 * abs(x-2)+4
plt.plot(x,y,)
plt.xticks(np.arange(-width, width+1, 1.0))
plt.yticks(np.arange(-hight, hight+1, 1.0))
plt.grid(True)
plt.show()
graph(10, 10)
"""
您的目标问题是您使用 linspace
创建的范围。此方法的默认样本数为 50,它们会均匀分配,因此根据您的 width
,2
可能不在此范围内。使用 num
参数(第三个位置)增加此值,它看起来会更好,但您的值可能仍不在范围内。
(问题是你正在处理一个数字列表,你不能处理无限集)。