venkatesannaveen / python-science-tutorial Goto Github PK
View Code? Open in Web Editor NEWSeries of notebooks to illustrate different plotting features using Python
License: MIT License
Series of notebooks to illustrate different plotting features using Python
License: MIT License
I'm brand new at this. Trying to create animated and interactive graphics in a JupyterBook for a classroom text that I'm writing. I found your examples of the Fermi-Dirac distribution in your nice Medium article of last year.
I can easily recreate the static diagram but when I try to create either the movie or the slider example I get errors. I've pasted in the two projects at the end of the first one (is that the right thing to do?) I'm working in Jupyter Lab, but my eventual target is JupyterBook. I'd appreciate some pointers.
BTW I know that making it work in a notebook is not how to make it work interactively in JupyterBook. If you have suggestions there, that would be very much appreciated!
I'm working on an M1 MacBook pro in, like I said, Jupyter Lab.
Python 3.8.8 (default, Apr 13 2021, 12:59:45)
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
Thanks in advance for your help and advice on web-embedding?
Here are the code and results:
Movie:
After the lines:
mpl.rcParams['xtick.major.size'] = 10
mpl.rcParams['xtick.major.width'] = 2
mpl.rcParams['ytick.major.size'] = 10
mpl.rcParams['ytick.major.width'] = 2
in the static program, I insert
# Change matplotlib backend
%matplotlib notebook
# Create figure and add axes
fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(111)
and so on
through to the end of your movie example code. It produces errors:
Javascript Error: Can't find variable: IPython
NameError Traceback (most recent call last)
<ipython-input-1-a0c46868fd22> in <module>
76
77 # Create animation
---> 78 ani = FuncAnimation(fig, animate, frames=range(len(T)), interval=500, repeat=True)
79
80 # Ensure the entire plot is visible
NameError: name 'FuncAnimation' is not defined
Sliders
In the same way, at the same point, I add the lines from the example:
fig = plt.figure(figsize=(6, 4.5))
# Create main axis
ax = fig.add_subplot(111)
fig.subplots_adjust(bottom=0.2, top=0.75)
and it produces a static picture of the plot with sliders (probably a slice of the animated gif from your article?) and errors
NameError Traceback (most recent call last)
<ipython-input-1-560d20080917> in <module>
72 plt.show()
73
---> 74 Slider.on_changed(func)
NameError: name 'func' is not defined
Here are the complete cells for both
Movie
# Import packages
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
# Fermi-Dirac Distribution
def fermi(E: float, E_f: float, T: float) -> float:
k_b = 8.617 * (10**-5) # eV/K
return 1/(np.exp((E - E_f)/(k_b * T)) + 1)
# General plot parameters
mpl.rcParams['font.family'] = 'Avenir'
mpl.rcParams['font.size'] = 18
mpl.rcParams['axes.linewidth'] = 2
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['xtick.major.size'] = 10
mpl.rcParams['xtick.major.width'] = 2
mpl.rcParams['ytick.major.size'] = 10
mpl.rcParams['ytick.major.width'] = 2
# Change matplotlib backend
%matplotlib notebook
# Create figure and add axes
fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(111)
# Temperature values
T = np.linspace(100, 1000, 10)
# Get colors from coolwarm colormap
colors = plt.get_cmap('coolwarm', 10)
# Plot F-D data
for i in range(len(T)):
x = np.linspace(0, 1, 100)
y = fermi(x, 0.5, T[i])
ax.plot(x, y, color=colors(i), linewidth=2.5)
# Add legend
labels = ['100 K', '200 K', '300 K', '400 K', '500 K', '600 K',
'700 K', '800 K', '900 K', '1000 K']
ax.legend(labels, bbox_to_anchor=(1.05, -0.1), loc='lower left',
frameon=False, labelspacing=0.2)
# Create figure and add axes
fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(111)
# Get colors from coolwarm colormap
colors = plt.get_cmap('coolwarm', 10)
# Temperature values
T = np.linspace(100, 1000, 10)
# Create variable reference to plot
f_d, = ax.plot([], [], linewidth=2.5)
# Add text annotation and create variable reference
temp = ax.text(1, 1, '', ha='right', va='top', fontsize=24)
# Set axes labels
ax.set_xlabel('Energy (eV)')
ax.set_ylabel('Fraction')
# Animation function
def animate(i):
x = np.linspace(0, 1, 100)
y = fermi(x, 0.5, T[i])
f_d.set_data(x, y)
f_d.set_color(colors(i))
temp.set_text(str(int(T[i])) + ' K')
temp.set_color(colors(i))
# Create animation
ani = FuncAnimation(fig, animate, frames=range(len(T)), interval=500, repeat=True)
# Ensure the entire plot is visible
fig.tight_layout()
# Save and show animation
ani.save('AnimatedPlot.gif', writer='imagemagick', fps=2)
plt.show()
Sliders
# Import packages
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.widgets import Slider
import numpy as np
import networkx as nx
from matplotlib.animation import FuncAnimation, PillowWriter
# Fermi-Dirac Distribution
def fermi(E: float, E_f: float, T: float) -> float:
k_b = 8.617 * (10**-5) # eV/K
return 1/(np.exp((E - E_f)/(k_b * T)) + 1)
# General plot parameters
mpl.rcParams['font.family'] = 'Avenir'
mpl.rcParams['font.size'] = 18
mpl.rcParams['axes.linewidth'] = 2
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['xtick.major.size'] = 10
mpl.rcParams['xtick.major.width'] = 2
mpl.rcParams['ytick.major.size'] = 10
mpl.rcParams['ytick.major.width'] = 2
fig = plt.figure(figsize=(6, 4.5))
# Create main axis
ax = fig.add_subplot(111)
fig.subplots_adjust(bottom=0.2, top=0.75)
# Create axes for sliders
ax_Ef = fig.add_axes([0.3, 0.85, 0.4, 0.05])
ax_Ef.spines['top'].set_visible(True)
ax_Ef.spines['right'].set_visible(True)
ax_T = fig.add_axes([0.3, 0.92, 0.4, 0.05])
ax_T.spines['top'].set_visible(True)
ax_T.spines['right'].set_visible(True)
# Create sliders
s_Ef = Slider(ax=ax_Ef, label='Fermi Energy ', valmin=0, valmax=1.0, valinit=0.5, valfmt=' %1.1f eV', facecolor='#cc7000')
s_T = Slider(ax=ax_T, label='Temperature ', valmin=100, valmax=1000, valinit=300, valfmt=' %i K', facecolor='#cc7000')
# Plot default data
x = np.linspace(-0, 1, 100)
Ef_0 = 0.5
T_0 = 300
y = fermi(x, Ef_0, T_0)
f_d, = ax.plot(x, y, linewidth=2.5)
# Update values
def update(val):
Ef = s_Ef.val
T = s_T.val
f_d.set_data(x, fermi(x, Ef, T))
fig.canvas.draw_idle()
s_Ef.on_changed(update)
s_T.on_changed(update)
# Set axis labels
ax.set_xlabel('Energy (eV)')
ax.set_ylabel('Fraction')
plt.show()
Slider.on_changed(func)
Awful that for the Gaussian fit you do not show correspondence between p0 and a, b, c,. Which is which?
That is, how does one define and or link here and in general the function parameters such as your a,b,c to e.g. p0=[5, -1, 1].
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.