Python:在包含两个不同变量的for循环内创建一个图

时间:2016-06-14 21:42:51

标签: python loops variables for-loop plot

我试图用两个参数绘制一个函数。在这种情况下,我喜欢关于" yy"为了使它在极坐标。当我运行该程序时,我获得10个数字而不是1个单独的情节。有这种情况发生的原因吗?而且,我根本没有得到一个情节。

import scipy.optimize as opt
import matplotlib.pyplot as plt
import pylab as pyl

freq = 9.75e9
lmda = 299792458./freq
k = 2*np.pi/lmda
h1 = 0.25*lmda



def theta(x,y):
    th = np.arctan(y,x)
    return th

def F(x,y):   
    f=2*np.abs(np.sin(k*h1*theta(x,y)))
    return f

def gain(x,y):
    return 10*np.log10(F(x,y)**2)

xx = np.arange(0,2000,200)
yy = np.linspace(0,np.pi/2,1000)

for tval in xx:

    plt.rcParams['text.latex.preamble']=[r'\usepackage{amsmath}']
    plt.rc('text',usetex=True)
    font = {'family':'serif','size':20}
    plt.rc('font',**font)
    fig, ax=plt.subplots(subplot_kw=dict(projection='polar'))
    ticks = np.arange(0,360,45)
    ax.set_ylim(-40,10)
    ax.set_yticks([-40,-30,-20,-10,0])
    ax.set_yticklabels(['','30','20','10',''],verticalalignment='center',horizontalalignment='center')
    ax.set_thetagrids(ticks, frac=1.2)
    ax.set_xlim(0, np.pi/2)
    ax.set_theta_zero_location('N') # changes the orienation of theta 
    ax.plot(yy,gain(yy,tval)) #dipole elevation plane pattern
    plt.tight_layout()
plt.show()

1 个答案:

答案 0 :(得分:0)

您需要进行一些重组:

import scipy.optimize as opt
import matplotlib.pyplot as plt
import pylab as pyl
import numpy as np

freq = 9.75e9
lmda = 299792458./freq
k = 2*np.pi/lmda
h1 = 0.25*lmda



def theta(x,y):
    th = np.arctan(y,x)
    return th

def F(x,y):   
    f=2*np.abs(np.sin(k*h1*theta(x,y)))
    return f

def gain(x,y):
    return 10*np.log10(F(x,y)**2)

xx = np.arange(0,2000,200)
yy = np.linspace(0,np.pi/2,1000)

plt.rcParams['text.latex.preamble']=[r'\usepackage{amsmath}']
plt.rc('text',usetex=True)
font = {'family':'serif','size':20}
plt.rc('font',**font)
fig, ax=plt.subplots(subplot_kw=dict(projection='polar'))
ticks = np.arange(0,360,45)
ax.set_ylim(-40,10)
ax.set_yticks([-40,-30,-20,-10,0])
ax.set_yticklabels(['','30','20','10',''],verticalalignment='center',horizontalalignment='center')
ax.set_thetagrids(ticks, frac=1.2)
ax.set_xlim(0, np.pi/2)
ax.set_theta_zero_location('N') # changes the orienation of theta 
for tval in xx:
    ax.plot(yy,gain(yy,tval)) #dipole elevation plane pattern

plt.tight_layout()
plt.show()

您还应该通过零错误处理除法。