Search code examples
pythonmatplotlibgraph

graph functions with range in python


It is my first question on stackoverflow, if I am missing some data, they tell me, What I need is to create a function graph with the python language but I do not find information on how to do it, I find how to make the graphs but not the limits of the functions

What I need to graph in python is similar to this function with the ranges enter image description here
This is the function

       { V₁x             0 ≤ x < a
       { V₁x - q(x-a)/2  a ≤ x ≤ a+l  # probably it's q(x-a)²/2
M(x) = { V₂(L-x)         a+l < x ≤ L
       { 0               otherwise



from matplotlib import pyplot as plt
x1 = [40, 50, 60, 70, 80, 90, 100]
y1 = [40, 50, 60, 70, 80, 90, 100]
plt.plot(x1, y1)
plt.xlabel('Like Geeks X Axis')
plt.ylabel('Like Geeks Y Axis')
axes = plt.axes()
axes.set_xlim([4, 8])
axes.set_ylim([-0.5, 2.5])
plt.show()

Solution

  • I think you can just create a function that reproduces your mathematical formulation and then get the ys using that function.

    If you need your code to be generic then do it like this:

    from matplotlib import pyplot as plt
    
    
    def create_function(V1, V2, a, l, q, L):
        def f(x):
            if x >= 0 and x < a:
                return V1 * x
            elif x >= a and x <= a + l:
                return V2 * x - q * (x - l)
            elif x > a + l and x <= L:
                return V2 * (L - x)
            return 0
    
        return f
    
    
    f = create_function(1, 2, 1, 2, 0.5, 5)
    
    x1 = list(range(15))
    y1 = list(map(f, x1))
    
    plt.plot(x1, y1)
    plt.xlabel("Like Geeks X Axis")
    plt.ylabel("Like Geeks Y Axis")
    plt.show()
    

    This way you have a generic function create_function that returns the function from your image with any parameter choice