简体   繁体   中英

Matplotlib why is the range on the x-axis wrong?

How do I make the second plot range between -4800 and 4800? What I've tried isn't working for some preposterous reason...

import math
import numpy as np
import matplotlib.pyplot as plt

f1 = np.arange(0, 9600, 1)
f2 = np.arange(-4800, 4800, 1)

def H1(f):
    w = 2*math.pi*f
    out = 1/(1+np.complex(0, 0.00006631455*w)) # required cut-off frequency of 2400 Hz
    return out

def magH1(f):
    out = np.absolute(H1(f))
    return out

def phaseH1(f):
    out = np.angle(H1(f))
    return out


magnitude = np.vectorize(magH1)
phase = np.vectorize(phaseH1)

plt.subplot(1, 2, 1)
plt.xticks(np.arange(0, 9600, 1200))
plt.xlabel('frequency (Hz)')
plt.ylabel('gain (V)')
plt.grid(True)
plt.plot(magnitude(f1))
plt.subplot(1, 2, 2)
plt.xticks(np.arange(-4800, 4800, 1200))
plt.xlabel('frequency (Hz)')
plt.ylabel('phase (radians)')
plt.grid(True)
plt.plot(phase(f2))
plt.show()

剧情形象

As you can see I highlighted the red area where the problem is, the range is incorrect for some bizarre reason. I would really appreciate some help with this horrendous issue.

I know you aren't supposed to say thanks at the end of a question, but all of your support is amazing to me.

Probably best to specify the x values when plotting. Here is a cleaned-up version:

fig, axs = plt.subplots(ncols=2, figsize=(10, 5))

axs[0].set_xticks(np.arange(0, 9600, 1200))
axs[0].set_xlabel('frequency (Hz)')
axs[0].set_ylabel('gain (V)')
axs[0].grid(True)
axs[0].plot(f1, magnitude(f1))

axs[1].set_xticks(np.arange(-4800, 4800, 1200))
axs[1].set_xlabel('frequency (Hz)')
axs[1].set_ylabel('phase (radians)')
axs[1].grid(True)
axs[1].plot(f2, phase(f2))

fig.tight_layout()
plt.show()

Output:

在此处输入图像描述

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