Matplotlib和Numpy:具有高阶数的记录图

时间:2017-09-12 23:06:03

标签: python numpy matplotlib

我正在尝试使用Matplotlib在一个绘图上绘制几个点,该绘图的行跟随energy()中定义的函数。这些点是等离子体参数,线条遵循使用多个德拜长度值连接它们的函数。

import matplotlib.pyplot as plt
import numpy as np

n_pts = [10**21,10**19,10**23,10**11,10**15,10**14,10**17,10**6]
KT_pts = [10000,100,1000,0.05,2,0.1,0.2,0.01]  

n_set = np.logspace(6,25)
debye_set = 7.43*np.logspace(-1,-7,10)

def energy(n,debye):
    return n*(debye/7430)**2

fig,ax=plt.subplots()

ax.scatter(n_pts,KT_pts)

for debye in debye_set:
    ax.loglog(n_set,energy(n_set,debye))

plt.show()

这会出现以下错误:

AttributeError: 'int' object has no attribute 'log'

1 个答案:

答案 0 :(得分:1)

对于大于64位整数(在64位系统上)的整数,Python会做自动的,奇怪的事情,比如10 ** 21。在这样做时,numpy将不会自动为这些对象使用numpy dtype,而是使用对象dtype。反过来,这不支持像np.log这样的ufunc:

> np.log([10**3])
array([ 6.90775528])
> np.log([10**30])
AttributeError: 'int' object has no attribute 'log'

这里的一个简单解决方案是确保numpy将n_pts(具有大数字的数组)转换为实际可以使用的dtype,如float:

import matplotlib.pyplot as plt
import numpy as np

n_pts = np.array([10**21,10**19,10**23,10**11,10**15,10**14,10**17,10**6], dtype='float')
KT_pts = [10000,100,1000,0.05,2,0.1,0.2,0.01]

n_set = np.logspace(6,25)
debye_set = 7.43*np.logspace(-1,-7,10)

def energy(n,debye):
    return n*(debye/7430)**2

fig,ax=plt.subplots()

ax.scatter(n_pts,KT_pts)

for debye in debye_set:
    ax.loglog(n_set,energy(n_set,debye))

plt.show()

output