Python Bokeh - Plotting Quadratic Curves on a Graph

Python Bokeh - Plotting Quadratic Curves on a Graph

Plotting quadratic curves using Bokeh in Python is a straightforward process. A quadratic curve is generally represented by the equation y=ax2+bx+c, where a, b, and c are constants. To plot this, you'll need to generate a range of x values, calculate the corresponding y values using the quadratic equation, and then plot these points using Bokeh.

Here's a step-by-step guide on how to do this:

Step 1: Install Bokeh

If you haven't already installed Bokeh, you can do so using pip:

pip install bokeh 

Step 2: Import Required Modules

Import Bokeh and other necessary modules in your Python script:

from bokeh.plotting import figure, show, output_file import numpy as np 

Step 3: Define Your Quadratic Function

Define a function to calculate the y values based on the quadratic formula:

def quadratic(x, a, b, c): return a * x**2 + b * x + c 

Step 4: Generate Data Points

Generate a range of x values and compute the corresponding y values. For example:

# Constants a, b, c a = 1 b = 0 c = 0 # Generate X values x = np.linspace(-10, 10, 200) # Calculate Y values y = quadratic(x, a, b, c) 

Step 5: Create a Bokeh Plot

Create a plot using Bokeh and add the quadratic curve to it:

# Create a Bokeh plot plot = figure(title="Quadratic Curve", x_axis_label='x', y_axis_label='y') # Add a line renderer with the quadratic data plot.line(x, y, legend_label="y = ax^2 + bx + c", line_width=2) # Specify the output file output_file("quadratic_curve.html") 

Step 6: Show the Plot

Finally, display the plot:

# Display the plot show(plot) 

Complete Example

Putting it all together, here's the complete script:

from bokeh.plotting import figure, show, output_file import numpy as np def quadratic(x, a, b, c): return a * x**2 + b * x + c a = 1 b = 0 c = 0 x = np.linspace(-10, 10, 200) y = quadratic(x, a, b, c) plot = figure(title="Quadratic Curve", x_axis_label='x', y_axis_label='y') plot.line(x, y, legend_label="y = ax^2 + bx + c", line_width=2) output_file("quadratic_curve.html") show(plot) 

When you run this script, it will create an HTML file named quadratic_curve.html and open it in your default web browser, displaying the plotted quadratic curve. You can adjust the constants a, b, and c to see how different quadratic curves look.


More Tags

fuzzy-logic controller-action collision lucene uisearchbardelegate donut-chart buffer handlebars.js utf-8 android-view

More Programming Guides

Other Guides

More Programming Examples