python-3.x - 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()
解决方案
我建议在绘图时使用 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')
推荐阅读
- excel - 区分大小写的 minif?
- chatbot - 为什么没有检测到我的通配符 + think + 条件?
- reactjs - 将 Formik 与 React.FC 一起使用
- c++ - 对 ofstream 的访问冲突
- java - OpenSubtitles API 响应
- bash - 如果满足条件,如何更新bash脚本中的一行
- reactjs - 我怎样才能做一个
每个参数的路径触发器“componentDidMount()”? - python - 我正在制作一个绘制线条的不和谐机器人,每次我多次使用 plot 命令时,它都会在上一个图表上绘制
- java - 查看作为 rt.jar 一部分的 sun.misc 的源代码
- sql - SQL - MS Access Form 设计 - 添加 ISA 关系数据