【问题标题】:Python - add green dots and red line to plotsPython - 在绘图中添加绿点和红线
【发布时间】: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


【解决方案1】:

对于红线,只需绘制正弦波的指数部分e^\frac{-x}{4},因为它会抑制正弦波。

对于绿点,绘制 x 轴的以下点: [x for x in range(21) if (x % 4) ==0] 以及它们被评估为 y 轴的衰减正弦波的结果

【讨论】:

    猜你喜欢
    • 2017-07-25
    • 1970-01-01
    • 2018-03-31
    • 2016-03-19
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 2020-12-11
    • 2020-09-08
    相关资源
    最近更新 更多