簡體   English   中英

Matplotlib繪圖時計算值-Python3

[英]Matplotlib compute values when plotting - python3

我想在繪制圖形時僅繪制正值(例如ML中的RELU函數)

這可能是一個愚蠢的問題。 我希望不是。

在下面的代碼中,我迭代並更改基礎列表數據。 我真的只想在繪圖時間更改值,而不更改源列表數據。 那可能嗎?

#create two lists in range -10 to 10
x = list(range(-10, 11))
y = list(range(-10, 11))

#this function changes the underlying data to remove negative values
#I really want to do this at plot time
#I don't want to change the source list. Can it be done?
for idx, val in enumerate(y):
    y[idx] = max(0, val)

#a bunch of formatting to make the plot look nice
plt.figure(figsize=(6, 6))
plt.axhline(y=0, color='silver')
plt.axvline(x=0, color='silver')
plt.grid(True)

plt.plot(x, y, 'rx')

plt.show()

我建議在繪制時使用numpy並過濾數據:

import numpy as np
import matplotlib.pyplot as plt

#create two lists in range -10 to 10
x = list(range(-10, 11))
y = list(range(-10, 11))

x = np.array(x)
y = np.array(y)

#a bunch of formatting to make the plot look nice
plt.figure(figsize=(6, 6))
plt.axhline(y=0, color='silver')
plt.axvline(x=0, color='silver')
plt.grid(True)

# plot only those values where y is positive
plt.plot(x[y>0], y[y>0], 'rx')

plt.show()

根本不會繪制y <0的點。 相反,如果您想將任何負值替換為零,則可以執行以下操作

plt.plot(x, np.maximum(0,y), 'rx')

看起來可能有點復雜,但可以動態過濾數據:

plt.plot(list(zip(*[(x1,y1) for (x1,y1) in zip(x,y) if x1>0])), 'rx')

說明:將數據成對處理以使(x,y)保持同步更加安全,然后必須將對轉換回單獨的xlist和ylist。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM