假設我有一個資料流,為簡單起見,將其設為貝爾曲線,從大范圍獲取:
import numpy as np
import matplotlib.pyplot as plt
def pdf(x, mean, std):
"""Return a PDF."""
y_out = 1/(std * np.sqrt(2 * np.pi)) * np.exp(-(x - mean)**2 / (2 * std**2))
return y_out
x = np.linspace(-1000, 1000, 20000)
y = 100 * pdf(x, 0, 1) np.random.normal(0, 1, 20000)
fig, ax = plt.subplots()
ax.plot(x, y)
由于 x 范圍太大,該圖將僅顯示一條非常窄的線,無論如何我們不需要在圖中包含所有噪聲。
在這種情況下,它可能是有意義的只顯示范圍繪制該[-20, 20]例如:ax.set_xlim([-20, 20])。但是,假設現在我們從另一次收購中得到了類似的資訊:
y = 100 * pdf(x, -50, 1) 100 * pdf(x, 0, 1) 100 * pdf(x, 40, 1) np.random.normal(0, 1, 20000)
使用這樣的函式,我們可能想要繪制更廣泛的范圍,例如ax.set_xlim([-70, 60]),以可視化獲取的所有信號。
有沒有辦法根據實際信號(即高于某個閾值的任何值,比如 10)以編程方式調整限制,而不必先繪制整個范圍,然后手動調整?
uj5u.com熱心網友回復:
使用
uj5u.com熱心網友回復:
與 Stef 的答案非常相似,不同之處在于我提出了一個最小寬度和一個額外的百分比,因此邊距將取決于x您想要顯示的數量,而不是邊距,因此您可以調整window_excess和min_width。如果您有很多情節要制作,這樣的事情可能會很有用。get_lims用這個替換 Stef 的函式會得到這樣的結果:
def get_lims(y, threshold = 10, window_excess = 0.5, min_width = 100):
minwidth = min_width / (1 window_excess)
a = np.argwhere(y > threshold)
da = max(minwidth, x[a[-1]] - x[a[0]])
ma = (x[a[-1]] x[a[0]]) / 2
minx = ma - da * (1 window_excess) / 2
maxx = ma da * (1 window_excess) / 2
return([minx, maxx])

您只需要添加一個檢查,xmin并且xmax在 x 的范圍內。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364270.html
標籤:Python matplotlib 阴谋
