Plots
MecSimCalc supports the two most popular plotting libraries:
- Matplotlib
- Plotly
Matplotlib
Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python.
Visit matplotlib.org for full documentation on how to use Matplotlib:
Once your Matplotlib figure is ready to be displayed, convert it to a HTML string using the mecsimcalc library as follows:
Code
import matplotlib.pyplot as plt
import numpy as np
import mecsimcalc as msc
def main(inputs):
# Create matplotlib figure
x = np.arange(0, 2, 0.01)
y = 2*(np.cos(4*x))
plt.plot(x, y)
# Convert figure to html using msc.print_plot()
plot_html = msc.print_plot(plt)
return {"plot": plot_html}
Output
{{ outputs.plot }}
See Example 2 in the introduction section for a detailed example on using Matplotlib.
Plotly
Plotly's Python graphing library makes interactive, publication-quality graphs.
Visit plotly.com/python for full documentation on how to use Plotly:
Once your Plotly figure is ready to be displayed, convert it to a HTML string that can be embedded into the outputs step. As follows:
Code
import plotly.express as px
import pandas as pd
import numpy as np
def main(inputs):
# Create plotly figure
x = np.arange(0, 2, 0.01)
y = 2*(np.cos(4*x))
fig = px.line(x, y, title="Cosine")
# Convert figure to html using to_html()
plot_html = fig.to_html(include_plotlyjs=True, full_html=False)
return {"plot": plot_html}
In .to_html()
, include_plotlyjs
must be set to True
for the plot to be displayed.
Output
{{ outputs.plot }}
Plotly Slider
Plotly is a plotting library similar to Matplotlib, but it also supports interactive plots. The MecSimCalc library provides a function to simplify creating a plotly figure with a slider.
MecSimCalc's plot_slider
function takes in a function as an argument and returns the plotly figure with a slider. The function has two arguments: the first argument is the value of the slider, and the second argument is the x value.
Code
import mecsimcalc as msc
def parabola(a, x): # a is the value of the slider
return a * x ** 2
def main(inputs):
a = inputs['a'] # initial value of the slider
plot_html = msc.plot_slider(parabola, x_range=(-10, 10), y_range=(-100, 100), initial_value=a, slider_range=(-10,10))
return {"plot": plot_html}