如何绘制不连续的上限函数?

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

这是我用来在 python 中绘制天花板函数图的代码。

import math
import numpy as np
import matplotlib.pyplot as plt 
x = np.arange(-5, 5, 0.01)
y = np.ceil(x)
plt.plot(x,y)
plt.xlabel('ceil(x)')
plt.ylabel('graph of ceil (x)')
plt.title('graph of ceil (x)')
plt.show()

我试过,

np.arange
考虑两个整数之间的浮点值,但是虽然无法绘制正确的图形,但该图形断开连接并在我们绘制数学时显示图形跳跃。

python numpy matplotlib floor ceil
2个回答
0
投票

我想这就是你想要的:

x = np.arange(-5, 5, 0.01)
y = np.ceil(x)

plt.xlabel('ceil(x)')
plt.ylabel('graph of ceil (x)')
plt.title('graph of ceil (x)')

for i in range(int(np.min(y)), int(np.max(y))+1):
    plt.plot(x[(y>i-1) & (y<=i)], y[(y>i-1) & (y<=i)], 'b-')

plt.show()


0
投票

如果您查看

y
,您会看到它只是数字,
1.0
等。
plot.plt(x,y)
显示连续的阶梯图。放大到足够大,您会发现垂直方向并非如此;他们显示了
y
1.0
2.0
的变化,在
x
中有一小步。

查看

x
的每第100个值。

In [13]: x[::100]
Out[13]:
array([-5.0000000e+00, -4.0000000e+00, -3.0000000e+00, -2.0000000e+00,
       -1.0000000e+00, -1.0658141e-13,  1.0000000e+00,  2.0000000e+00,
        3.0000000e+00,  4.0000000e+00])

在这些点上看

ceil
,然后:

In [15]: np.ceil(x[::100])
Out[15]: array([-5., -4., -3., -2., -1., -0.,  1.,  2.,  3.,  4.])
In [16]: np.ceil(x[1::100])
Out[16]: array([-4., -3., -2., -1., -0.,  1.,  2.,  3.,  4.,  5.])

我们可以在每次跳跃时将

y
更改为
np.nan
.

In [17]: y[::100]=np.nan

然后

plt(x,y)
将跳过
nan
值,并仅显示没有近垂直立管的平面。

连接

y
中的红色破折号,蓝色是与
nan
值断开连接。

另一个答案为每个级别做一个单独的

plot

有评论建议

stair
,但我还没有弄清楚调用细节

在任何情况下,断开连接的绘图都需要对绘图进行特殊处理。仅仅创建

x,y
数组是不够的。

© www.soinside.com 2019 - 2024. All rights reserved.