简体   繁体   中英

Parametric plot in Python using matplotlib

I'm trying to plot two functions of time parametrically using matplotlib in Python 2.7. Here's what I'm attempting to do in my code:

import matplotlib.pyplot as plt
import numpy as np

def x(t, x_0, w):
    return x_0*np.cos(w*t)
def x_prime(t, x_0, w):
    return -x_0*w*np.sin(w*t)

# for x_0 = w = 1:
t_range = np.arange(0, 2*np.pi, np.pi/4)
for t in t_range:
    plt.plot(x(t, 1, 1), x_prime(t, 1, 1))
plt.show()

However, nothing is showing up on my plot. The axes are labeled but nothing is graphed. I've plotted within for loops before without any problem, so why is this happening here?

The for loop is your problem.

Here:

plt.plot(x(t, 1, 1), x_prime(t, 1, 1))

Since t is one value and not a list because of your for loop, the X and y that you are trying to plot are just individual points. Individual points don't show up on matplotlib if you don't specify their markersize and the marker. You can fix this by just plotting all the points at once to form a line:

def x(t, x_0, w):
    print(x)
    return x_0*np.cos(w*t)
def x_prime(t, x_0, w):
    return -x_0*w*np.sin(w*t)

t_range = np.arange(0, 2*np.pi, np.pi/4)

plt.plot(x(t_range, 1, 1), x_prime(t_range, 1, 1))
plt.show()

If instead you still want to use the for-loop method to plot points you need to add extra parameters:

t_range = np.arange(0, 2*np.pi, np.pi/4)
for t in t_range:
    print(x(t, 1, 1,), x_prime(t, 1, 1))
    plt.plot(x(t, 1, 1), x_prime(t, 1, 1), markersize=3, marker='o')

plt.show()

Edit: To make it go all the way around you simply add the first point again to the end of your arrays:

a = x_prime(t_range, 1, 1)
b = x(t_range, 1, 1)
a = np.append(a, [a[0]])
b = np.append(b, [b[0]])

plt.plot(a, b)
plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM