【问题标题】:Creating a graph from a math function从数学函数创建图形
【发布时间】:2016-01-24 06:33:51
【问题描述】:

我在学习用 python 绘制函数时遇到了麻烦。例如我想用这两个函数创建一个图表:

y=10x
y=5x+20

我发现的唯一方法是使用以下代码

import matplotlib.pyplot as plt
plt.plot([points go here], [points go here])
plt.plot([points go here], [points go here])
plt.ylabel('some numbers')
plt.show()

并手动输入数据点,但我遇到了一些更棘手的问题,所以这真的很困难。

有没有办法只输入我需要绘制的函数并让 python 为我创建图表?

【问题讨论】:

    标签: python function math matplotlib graph


    【解决方案1】:

    这很粗糙,但它会起作用:

    import matplotlib.pyplot as plt
    import random 
    
    x = [1, 2, 4,6, 7, 100, 200, 100, 34]
    tenxArray = []
    fiveXPlusTwenty = []
    
    for i in range(0, len(x)):
        tenxArray.append(10*x[i])
        fiveXPlusTwenty.append(5*x[i] + 20)
    
    plt.plot(x, tenxArray)
    plt.plot(x, fiveXPlusTwenty)
    
    plt.show()
    

    【讨论】:

      【解决方案2】:

      您可以使用 range 生成器来生成 x 值和列表推导来计算函数的 y 值:

      import matplotlib.pyplot as plt
      
      def fun1(x):
          return 10*x
      
      def fun2(x):
          return 5*x+20
      
      MAX_X = # A maximum value for x goes here
      x = range(MAX_X)
      
      y1,y2 = zip(*[ (fun1(val), fun2(val)) for val in x ])
      
      plt.plot(x, y1)
      plt.plot(x, y2)
      plt.ylabel('some numbers')
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多