将此函数绘制为累积分布

时间:2019-02-05 19:03:11

标签: python numpy matplotlib statistics

我正在尝试使用-infinity到infinity在Python中创建以下函数的累积分布图:

enter image description here

最初,我尝试了在网上找到的这段代码,该代码似乎适用于x ** 2之类的功能:

import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
    x = np.array(x_range)
    y = eval(formula)
    plt.plot(x, y)
    plt.show()

#graph('(4/5)*(((x**4)/4)+x)', range(-100, 100))

graph('x**2', range(-100, 100))

结果: enter image description here

问题是我不确定如何转换此代码以将函数的其他条件考虑到此图中(即,如果x <= 0,则为0,如果x> = 1,则为0)。如果无法修改此代码以考虑到这两个条件,那么是否有其他建议可以做到这一点?

1 个答案:

答案 0 :(得分:2)

您可以将条件用作掩码,然后利用NumPy数组索引为想要的区域将y的值分配为0。

变更夫妇:

  • 我使用linspace进行了精细划分,以便在x=0x=1之间包含更多数据点。您使用的range会生成整数,因此基本上您将在0到1之间有一条直线。
  • y[(x<=0) | (x>=1)] = 0是这里的关键。 |运算符合并两个条件(x<=0) | (x>=1)并从x数组返回索引,其中该条件保存True。然后将这些索引用作y数组的输入,然后将这些值分配为0。

我将x限制限制为-1.5到1.5,以突出显示有趣的区域。

完整回答x ^ 2种情况

import numpy as np
import matplotlib.pyplot as plt
def graph(formula, x_range):
    x = np.array(x_range)
    y = eval(formula)

    y[(x<=0) | (x>=1)] = 0
    plt.plot(x, y)
    plt.xlim(-1.5,1.5)
    plt.show()

graph('x**2', np.linspace(-100, 100, 10000))

绘制实际方程式

import numpy as np
import matplotlib.pyplot as plt

def graph(formula, x_range):
    x = np.array(x_range)
    y = eval(formula)

    y[(x<=0) | (x>=1)] = 0
    plt.plot(x, y)
    plt.xlim(-1.5,1.5)
    plt.show()

graph('(4/5)*(((x**4)/4)+x)', np.linspace(-100, 100, 10000))

enter image description here

enter image description here

相关问题