Graphing a parabola with inputs in matplotlib

Question:

so I’ve created a quadratic equation solver in python, and I want a graph to go along with it. I want this graph to depict the parabola.

a = an input for a in quadratic equation

b = an input for b in quadratic equation

c = an input for c in quadratic equation

y = -b/2*a (vector)

import math
a = int(input('Input a: '))
b = int(input('Input b: '))
c = int(input('Input c: '))
discrim = int((b*b) - 4*a*c) 
posi = (-b + (math.sqrt(discrim)))/(2*a)
neg = (-b - (math.sqrt(discrim)))/(2*a)


if b > 0 and c > 0 and posi < 0:
  posi = -posi
  if neg < 0:
    neg = -neg

y = -b/2*a
vector = (neg+posi)/2, y)

With this code, I have my x intercept(s), and the vector, which is enough to create a parabola, I’m just not sure how to turn these values into a graph using MatPlotLib. Please ask any questions.

Asked By: Thomas Kelly

||

Answers:

I have made some corrections in You code. Below code will plot any parabola. You can add zero points and extreme point into you plot.

import matplotlib.pyplot as plt
import math
import numpy as np

a = int(input('Input a: '))
b = int(input('Input b: '))
c = int(input('Input c: '))

# calculate delta and zero points
delta = b**2 - 4*a*c
if delta > 0:
    x_1 = (-b + math.sqrt(delta))/(2*a)
    x_2 = (-b - math.sqrt(delta))/(2*a)
if delta == 0:
    x_0 = -b/(2*a)
else:
    pass

# calculate parabola extreme coordinates
p = -b/(2*a)
q = -delta/(4*a)
extreme = [p,q]

# define parabola function
def parabola(x,a,b,c):
    y = a*x**2 + b*x + c
    return y

# plot function
x = np.linspace(int(p)-5,int(p)+5,100)
y = parabola(x,a,b,c)
plt.plot(x,y)
plt.axhline(y=0, color='black', linestyle='-')
plt.axvline(x=0, color='black', linestyle='-')
plt.text(p-0.5, q-3, '[' + str(round(p,2)) +',' + str(round(q,2)) + ']',color='orange', fontsize=9)
plt.plot(p, q, marker="o")

if delta > 0:
    plt.plot(x_1, 0, marker="o", color='green')
    plt.text(x_1 - 0.5, 2, '[' + str(round(x_1,2)) + ']', color='green', fontsize=9)
    plt.plot(x_2, 0, marker="o", color='green')
    plt.text(x_2 - 0.5, 2, '[' + str(round(x_2,2)) + ']', color='green', fontsize=9)

if delta == 0:
    plt.plot(x_0, 0, marker="o", color='green')
    plt.text(x_0 - 0.5, 2, '[' + str(round(x_0,2)) + ']', color='green', fontsize=9)

plt.show()

Sample result:

enter image description here

Answered By: Zaraki Kenpachi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.