python - 从 matplotlib 获取阶跃函数值
问题描述
我有 2 个带有数据的 numpy 数组,比如说x,y
,我申请plt.step()
并获得它的连续(步进)曲线。
我希望能够自己创建此函数,这意味着我希望对原始数组中实际上不存在的y
for的值进行(零阶保持)步长近似。x
x
例如,在以下链接中,我想要“新”实际矩形正弦值,而不仅仅是绘制: https ://matplotlib.org/gallery/lines_bars_and_markers/step_demo.html#sphx-glr-gallery-lines-bars -and-markers-step-demo-py
解决方案
您可以使用 scipy 的interp1d创建步进函数。默认插值是“线性”,但您可以将其更改为“下一个”、“上一个”或“最近的”以获得阶跃函数。
一个标准的阶跃函数是从中获得的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()
推荐阅读
- amazon-web-services - AWS IoT 子物?
- azure - 是否可以使用从 SQL 生成的 file_data json 对象作为 Azure 搜索文档提取认知技能的输入?
- azure-blob-storage - Word office js 插件 - 为什么访问 blob 可以在本地/调试而不是生产
- javascript - 将 XMLHttpRequest.responseText 保存在 GTM 的变量中
- python-3.x - 无法在 virtualenv 中运行 protoc
- r - 如何跨多列将 1、2、3、4 更改为 0、1?
- ios - 应用程序在后台时未调用 iOS 发布模式的后台消息处理程序 [FCM,Flutter]
- keycloak - Slowloris 的 keycloak 设置 - mod_reqtimeout
- r - 如何找到第三名的学生?
- javascript - 如何从新的 MetaMask 以太坊 API 中获取账户列表?