从 matplotlib 获取阶跃函数值
Get step function values from matplotlib
我有 2 个带有数据的 numpy 数组,比如 x,y
,我应用 plt.step()
并得到它的连续(步长)曲线。
我希望能够自己创建此函数,这意味着我希望对 x
的 y
的值进行(零阶保持)阶跃近似实际上存在于原始x
数组中。
例如,在下面的 link 中,我想要 'new' 实际矩形正弦值,而不仅仅是绘制:
https://matplotlib.org/gallery/lines_bars_and_markers/step_demo.html#sphx-glr-gallery-lines-bars-and-markers-step-demo-py
您可以随意选择刻度值和对应的函数值。这是一个不等距参数及其值的示例:
x = np.arange(20) + np.random.random(20)/2
y = np.sin(x / 2)**2 + np.random.random(20)/5
注意:这两个数组的大小必须相等。如果你想要自己的自定义函数,你可以使用np.vectorise
:
x = np.arange(20) + np.random.random(20)/2
func = np.vectorize(lambda x: np.sin(x) + np.random.random()/5)
y = func(x)
您可以使用 scipy 的 interp1d 创建阶跃函数。默认插值是 'linear',但您可以将其更改为 'next'、'previous' 或 'nearest' 作为阶跃函数。
从step_fun = interp1d(x, y, kind='previous')
得到一个标准的阶跃函数,然后调用它作为step_fun(new_x)
。
以下代码比较了不同类型的“插值”:
from matplotlib import pyplot as plt
import numpy as np
from scipy.interpolate import interp1d
x = np.random.uniform(0.1, 0.7, 20).cumsum()
y = np.sin(x)
kinds = ['linear', 'previous', 'next', 'nearest', 'cubic']
for i, kind in enumerate(kinds):
function_from_points = interp1d(x, y + i, kind=kind)
x_detailed = np.linspace(x[0], x[-1], 1000)
plt.plot(x_detailed, function_from_points(x_detailed), color='dodgerblue')
plt.scatter(x, y + i, color='crimson')
plt.yticks(range(len(kinds)), kinds)
plt.show()
我有 2 个带有数据的 numpy 数组,比如 x,y
,我应用 plt.step()
并得到它的连续(步长)曲线。
我希望能够自己创建此函数,这意味着我希望对 x
的 y
的值进行(零阶保持)阶跃近似实际上存在于原始x
数组中。
例如,在下面的 link 中,我想要 'new' 实际矩形正弦值,而不仅仅是绘制: https://matplotlib.org/gallery/lines_bars_and_markers/step_demo.html#sphx-glr-gallery-lines-bars-and-markers-step-demo-py
您可以随意选择刻度值和对应的函数值。这是一个不等距参数及其值的示例:
x = np.arange(20) + np.random.random(20)/2
y = np.sin(x / 2)**2 + np.random.random(20)/5
注意:这两个数组的大小必须相等。如果你想要自己的自定义函数,你可以使用np.vectorise
:
x = np.arange(20) + np.random.random(20)/2
func = np.vectorize(lambda x: np.sin(x) + np.random.random()/5)
y = func(x)
您可以使用 scipy 的 interp1d 创建阶跃函数。默认插值是 'linear',但您可以将其更改为 'next'、'previous' 或 'nearest' 作为阶跃函数。
从step_fun = interp1d(x, y, kind='previous')
得到一个标准的阶跃函数,然后调用它作为step_fun(new_x)
。
以下代码比较了不同类型的“插值”:
from matplotlib import pyplot as plt
import numpy as np
from scipy.interpolate import interp1d
x = np.random.uniform(0.1, 0.7, 20).cumsum()
y = np.sin(x)
kinds = ['linear', 'previous', 'next', 'nearest', 'cubic']
for i, kind in enumerate(kinds):
function_from_points = interp1d(x, y + i, kind=kind)
x_detailed = np.linspace(x[0], x[-1], 1000)
plt.plot(x_detailed, function_from_points(x_detailed), color='dodgerblue')
plt.scatter(x, y + i, color='crimson')
plt.yticks(range(len(kinds)), kinds)
plt.show()