1

我正在尝试创建一个 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)*1.e-10
temperature=[3000,4000,5000,6000]

for lam in wavelengths:
    for T in temperature:
        B_lambda = ((2*h*c**2)/(lam**5))*((1)/(np.exp((h*c)/(lam*k*T))-1))
        plt.figure()
        plt.plot(wavelengths,B_lambda)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-73b866241c49> in <module>
     17         B_lambda = ((2*h*c**2)/(lam**5))*((1)/(np.exp((h*c)/(lam*k*T))-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, *args, **kwargs)
   2787     return gca().plot(
   2788         *args, 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, *args, **kwargs)
   1663         """
   1664         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D._alias_map)
-> 1665         lines = [*self._get_lines(*args, 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, *args, **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,)```
4

1 回答 1

0

首先要注意(这是次要的)是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)*1.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*h*c**2)/(lam**5))*((1)/(np.exp((h*c)/(lam*k*T))-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(*zip(*outputs))

在此处输入图像描述

另一种方法是将数据显示为图像,使用颜色来指示函数输出。

我还包括另一种生成数据的方法。由于该函数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)]
         )

在此处输入图像描述

于 2020-03-08T14:59:12.677 回答