user308827
user308827

Reputation: 21961

plotting sympy results in python

I am using sympy to solve for b1 and b2:

y=x/[x+exp(b1-b2*x)]
x1 = 90; y1 = 0.05 and x2=99;y2=0.95


import sympy
b1,b2 = symbols('b1 b2')
solve([Eq(90*0.05+90*exp(b1-(b2*90))-90, 0.0), Eq(99*0.95+99*exp(b1-(b2*99))-99, 0.0)], [b1, b2])

>>> {b1:29.3930964972769,b2:0.327159886574049}

How do I use these results to plot a S-shaped curve constrained by these values. Y-axis ranges from 0 to 1. x1,y1 and x2,y2 are 2 points on that curve.

Upvotes: 3

Views: 12091

Answers (2)

ptb
ptb

Reputation: 2148

Using the latest versions of sympy and ipython

In [1]: from sympy import *

In [2]: x, b1, b2 = symbols("x b1 b2")

In [3]: f = x/(x+exp(b1-b2*x))

In [4]: res = {b1:29.3930964972769,b2:0.327159886574049}

In [5]: plot(f.subs(res), (x, 0, 100))

With the output figure: enter image description here

Upvotes: 6

ljetibo
ljetibo

Reputation: 3094

Sympy allegedly has it's own plotting functionality, but I couldn't get it to work from the manual they had. I'm not an active user of sympy.

But here's a version on how to do it with numpy and matplotlib

  • Define your function so it can act on a np.array
  • Spread points uniformly in some range "x"
  • act on those points with your function "y"
  • plot the set of uniformly spaced points "x" vs function values in those points "y"

    import numpy as np
    import matplotlib.pyplot as plt
    
    def f(a):
       c1 = 0.327159886574049
       c2 = 29.3930964972769
       return a/(a+np.exp(c1-c2*a))
    
    x = np.linspace(0, 1, 500)
    y = f(x)
    plt.plot(x,y)
    plt.show()
    

You should get something like this:

enter image description here

Upvotes: 4

Related Questions