【发布时间】:2022-01-13 00:56:51
【问题描述】:
对于硬件,我正在尝试创建子图并重新创建此特定图:
这是我目前的代码:
import numpy as np
import matplotlib.pyplot as plt
nmax=101 # choose a high number to "smooth out" lines in plots
x = np.linspace(0,20,nmax) # create an array x
y = np.exp(-x/4)*np.sin(x)
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(x, y)
axs[0, 0].set_title(r'$y = e^\frac{-x}{4} sin(x)$')
axs[0, 0].set_xlabel('x')
axs[0, 0].grid(color='blue', linestyle='--', linewidth=1.0)
axs[0, 0].set_xlim([0, 20])
axs[0, 0].set_yticks([-0.5,0.0,0.5,1.0])
axs[0, 1].plot(x, y, 'tab:blue')
axs[0, 1].set_title(r'$y = e^\frac{-x}{4} sin(x)$')
axs[0, 1].set_xlabel('x')
axs[0, 1].grid(color='blue', linestyle='--', linewidth=1.0)
axs[0, 1].set_xlim([0, 20])
axs[0, 1].set_yticks([-0.5,0.0,0.5,1.0])
我知道如何在代码中添加点和线,但是如何指定代码以在可被 4 整除的位置添加红色虚线和绿点?对于绿点,我试过了,
for i in x:
if i % 4 == 0:
axs[0, 1].plot(x[i], y[i], 'go')
但这会导致错误:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-48-9236638b38a7> in <module>
32 for i in x:
33 if i % 4 == 0:
---> 34 axs[0, 1].plot(x[i], y[i], 'go')
35
36
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
【问题讨论】:
-
错误来自
i不是整数。x[4]是允许的,但x[4.0]是不允许的。 -
for i in range(len(x))
标签: python matplotlib