Home > Net >  Python - add green dots and red line to plots
Python - add green dots and red line to plots

Time:01-14

For a HW, I am trying to create subplots and recreate this specific plot:

enter image description here

This is my code so far:

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])

I know how to add points and lines to my code, but how do I specify my code to add that dashed red line and the green dots at places divisible by 4? For the green dots, I tried,

for i in x:
    if i % 4 == 0:
        axs[0, 1].plot(x[i], y[i], 'go')  

But this results in an error:

---------------------------------------------------------------------------
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

CodePudding user response:

for the red line just plot the exponential part e^\frac{-x}{4} of your sine wave, since is the one dampening your sine wave.

and for the green dots plot the following points for x axis: [x for x in range(21) if (x % 4) ==0] and their result of being evaluated into your dampened sine wave for the y axis

  •  Tags:  
  • Related