使用matplotlib绘制函数

时间:2015-10-21 16:05:50

标签: python function numpy matplotlib plot

所以我定义了一个函数,由于某种原因,终端返回了以下错误:

TypeError: only length-1 arrays can be converted to Python scalars

我不确定我做错了什么?

这是我自包含的函数,带有相应的图:

import matplotlib
import math
import numpy
import matplotlib.pyplot as pyplot
import matplotlib.gridspec as gridspec

def rotation_curve(r):
    v_rotation = math.sqrt((r*(1.33*(10**32)))/(1+r)**2)
    return v_rotation

curve_range = numpy.linspace(0, 100, 10000)

fig = pyplot.figure(figsize=(16,6))

gridspec_layout = gridspec.GridSpec(1,1)
pyplot = fig.add_subplot(gridspec_layout[0])

pyplot.plot(curve_range, rotation_curve(curve_range))

matplotlib.pyplot.show()

有人可以告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:1)

问题在于rotation_curve(r)的定义。您输入并操作了一个numpy数组(curve_range),但是使用非向量化函数math.sqrt来执行此操作:

v_rotation = math.sqrt((r*(1.33*(10**32)))/(1+r)**2)

相反,使用numpy.sqrt在数组中的每个元素上广播sqrt操作。乘法和取幂运算符在numpy数组中重载,因此这些应该可以正常工作。

def rotation_curve(r):
    v_rotation = numpy.sqrt((r*(1.33*(10**32)))/(1+r)**2)
    return v_rotation