首页 > 解决方案 > Matplotlib 绘图时计算值 - 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()

标签: python-3.xmatplotlib

解决方案


我建议在绘图时使用 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')

推荐阅读