开发者社区 问答 正文

如何正确编写用于执行和绘制for循环操作的语法?

我正在尝试创建一个for循环,该循环使用定义的函数(B_lambda)并接受波长和温度值以产生强度值。即,我希望循环采用函数B_lambda并遍历温度列表中每个温度在我列出的波长范围内的每个值。然后,我想绘制结果。我对语法不是很好,并且尝试了很多方法,但是没有什么能满足我的需要,而且我大多会出错。我不知道如何使用for循环进行绘制,而我已经签出的所有在线资源都没有帮助我在for循环中使用定义的函数。我将在下面显示错误消息最少的最新代码:

import matplotlib.pylab as plt
import numpy as np
from astropy import units as u
import scipy.constants
%matplotlib inline

#Importing constants to use.
h = scipy.constants.h
c = scipy.constants.c
k = scipy.constants.k

wavelengths= np.arange(1000,30000)\*.e-10
temperature=[3000,4000,5000,6000]

for lam in wavelengths:
    for T in temperature:
        B_lambda = ((2\*\*\*2)/(lam\*5))\*(1)/(np.exp((h\*)/(lam\*\*))-1))
        plt.figure()
        plt.plot(wavelengths,B_lambda)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-73b866241c49> in <module>
     17         B_lambda = ((2\*\*\*2)/(lam\*5))\*(1)/(np.exp((h\*)/(lam\*\*))-1))
     18         plt.figure()
---> 19         plt.plot(wavelengths,B_lambda)
     20 
     21 

/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py in plot(scalex, scaley, data, \*rgs, \*kwargs)
   2787     return gca().plot(
   2788         \*rgs, scalex=scalex, scaley=scaley, \*({"data": data} if data
-> 2789         is not None else {}), \*kwargs)
   2790 
   2791 

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_axes.py in plot(self, scalex, scaley, data, \*rgs, \*kwargs)
   1663         """
   1664         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
-> 1665         lines = [\*elf._get_lines(\*rgs, data=data, \*kwargs)]
   1666         for line in lines:
   1667             self.add_line(line)

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in __call__(self, \*rgs, \*kwargs)
    223                 this += args[0],
    224                 args = args[1:]
--> 225             yield from self._plot_args(this, kwargs)
    226 
    227     def get_next_color(self):

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _plot_args(self, tup, kwargs)
    389             x, y = index_of(tup[-1])
    390 
--> 391         x, y = self._xy_from_xy(x, y)
    392 
    393         if self.command == 'plot':

/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in _xy_from_xy(self, x, y)
    268         if x.shape[0] != y.shape[0]:
    269             raise ValueError("x and y must have same first dimension, but "
--> 270                              "have shapes {} and {}".format(x.shape, y.shape))
    271         if x.ndim > 2 or y.ndim > 2:
    272             raise ValueError("x and y can be no greater than 2-D, but have "

ValueError: x and y must have same first dimension, but have shapes (29000,) and (1,) \`  \`  \` 

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 22:49:16 1033 分享 版权
1 条回答
写回答
取消 提交回答
  • 要注意的第一件事(这是次要的)是运行代码不需要astropy。因此,您可以简化导入语句。

    import matplotlib.pylab as plt
    import numpy as np
    import scipy.constants
    %matplotlib inline
    
    #Importing constants to use.
    h = scipy.constants.h
    c = scipy.constants.c
    k = scipy.constants.k
    
    
    wavelengths= np.arange(1000,30000,100)\*.e-10 # here, I chose steps of 100, because plotting 29000 datapoints takes a while
    temperature=[3000,4000,5000,6000]
    

    其次,要整理一下循环,可以编写一个辅助函数,您可以在循环内部调用该函数:

    def f(lam, T):
        return ((2\*\*\*2)/(lam\*5))\*(1)/(np.exp((h\*)/(lam\*\*))-1))
    

    现在您可以收集函数的输出以及输入参数,例如在元组列表中:

    outputs = []
    
    for lam in wavelengths:
        for T in temperature:
            outputs.append((lam, T, f(lam, T)))
    

    由于您同时改变波长和温度,因此3d图很有意义:

    from mpl_toolkits.mplot3d import Axes3D
    
    fig = plt.figure(figsize=(10,10))
    ax = fig.add_subplot(111, projection='3d')
    
    ax.plot(\*ip(\*utputs))
    

    另一种选择是将数据显示为图像,使用颜色指示功能输出。

    我还将在此方法中包括另一种生成数据的方法。由于函数“ f”可以将数组作为输入,因此您可以一次输入一个温度,并同时输入所有波长。

    # initialise output as array with proper shape
    outputs = np.zeros((len(wavelengths), len(temperature)))
    
    for i, T in enumerate(temperature):
        outputs[:,i] = f(wavelengths, T)
    

    现在的输出是一个大矩阵,您可以将其可视化为图像:

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.imshow(outputs, aspect=10e8, interpolation='none', 
              extent=[
                  np.min(temperature),
                  np.max(temperature),
                  np.max(wavelengths),
                  np.min(wavelengths)]
             )
    

    回答来源:stackoverflow

    2020-03-24 22:49:25
    赞同 展开评论
问答分类:
问答地址: