Search code examples
pythonnumpymatplotlibcurvetrigonometry

Python maplotlib sine curve with random.randn


I am pretty new to Python and have following question:

I generated numpy arrays with the following code:

X = np.random.randn(1000)*2
Y = np.sin(x)

How can I obtain a visualization of above data which looks similar to:

enter image description here

Thank you guys for any help!


Solution

  • If you use matplotlib.pyplot you can plot them as a scatter plot and get a rough approximation of a sine wave.

    For example using your x and y arrays:

    import matplotlib.pyplot as plt
    import numpy as np
    
    X = np.random.rand(1000)*2
    Y = np.sin(X)
    plt.scatter(X,Y)
    plt.show()
    

    You'll end up with something like this:

    enter image description here

    EDIT Per your comment I ran this for you:

    sortx = np.argsort(X)
    plt.plot(X[sortx], Y[sortx], marker='.')
    plt.show()
    

    You'll get this approximation: enter image description here

    You have to pass the argsort indices into X so that it plots them in the correct order and do the same for Y that way you get a nice smooth line (at least for where your data is most dense).

    If you want a smooth line representation of the sine wave then you could just say:

    z = np.arange(-6.28, 6.28, 0.1)
    plt.plot(z, np.sin(z))
    plt.show()
    

    You'll end up with this: enter image description here

    Obviously, you may want to adjust the x axis ticks to represent values of pi for a better representation, but i think you get the idea.