14.1. Matplotlib#
import matplotlib.pyplot as plt
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[1], line 1
----> 1 import matplotlib.pyplot as plt
ModuleNotFoundError: No module named 'matplotlib'
%matplotlib inline
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[2], line 1
----> 1 get_ipython().run_line_magic('matplotlib', 'inline')
File ~/anaconda3/envs/book_notes/lib/python3.13/site-packages/IPython/core/interactiveshell.py:2504, in InteractiveShell.run_line_magic(self, magic_name, line, _stack_depth)
2502 kwargs['local_ns'] = self.get_local_scope(stack_depth)
2503 with self.builtin_trap:
-> 2504 result = fn(*args, **kwargs)
2506 # The code below prevents the output from being displayed
2507 # when using magics with decorator @output_can_be_silenced
2508 # when the last Python token in the expression is a ';'.
2509 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):
File ~/anaconda3/envs/book_notes/lib/python3.13/site-packages/IPython/core/magics/pylab.py:103, in PylabMagics.matplotlib(self, line)
98 print(
99 "Available matplotlib backends: %s"
100 % _list_matplotlib_backends_and_gui_loops()
101 )
102 else:
--> 103 gui, backend = self.shell.enable_matplotlib(args.gui)
104 self._show_matplotlib_backend(args.gui, backend)
File ~/anaconda3/envs/book_notes/lib/python3.13/site-packages/IPython/core/interactiveshell.py:3787, in InteractiveShell.enable_matplotlib(self, gui)
3784 import matplotlib_inline.backend_inline
3786 from IPython.core import pylabtools as pt
-> 3787 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
3789 if gui != None:
3790 # If we have our first gui selection, store it
3791 if self.pylab_gui_select is None:
File ~/anaconda3/envs/book_notes/lib/python3.13/site-packages/IPython/core/pylabtools.py:338, in find_gui_and_backend(gui, gui_select)
321 def find_gui_and_backend(gui=None, gui_select=None):
322 """Given a gui string return the gui and mpl backend.
323
324 Parameters
(...) 335 'WXAgg','Qt4Agg','module://matplotlib_inline.backend_inline','agg').
336 """
--> 338 import matplotlib
340 if _matplotlib_manages_backends():
341 backend_registry = matplotlib.backends.registry.backend_registry
ModuleNotFoundError: No module named 'matplotlib'
x = list(range(10))
y = [ele*ele for ele in x]
x
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Method 1
# A simple plot
plt.plot(x,y)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[6], line 3
1 # Method 1
2 # A simple plot
----> 3 plt.plot(x,y)
NameError: name 'plt' is not defined
plt.plot(x,y, 'r.')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[7], line 1
----> 1 plt.plot(x,y, 'r.')
NameError: name 'plt' is not defined
plt.plot(x,y,
linewidth=2,
linestyle='-.',
color='red',
marker='o',
markersize=20,
markeredgewidth=2,
markeredgecolor='lawngreen',
markerfacecolor='black',
)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[8], line 1
----> 1 plt.plot(x,y,
2 linewidth=2,
3 linestyle='-.',
4 color='red',
5 marker='o',
6 markersize=20,
7 markeredgewidth=2,
8 markeredgecolor='lawngreen',
9 markerfacecolor='black',
10 )
NameError: name 'plt' is not defined
# Shortcut for controlling the line style and color
# plt.plot(x,y, 'y--')
# https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.plot.html
plt.plot(x,y,
linewidth=1,
linestyle='--',
color='red',
marker='o',
markersize=15,
markeredgewidth=3,
markeredgecolor='blue',
markerfacecolor='black',
fillstyle='left')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[9], line 5
1 # Shortcut for controlling the line style and color
2 # plt.plot(x,y, 'y--')
3 # https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.plot.html
----> 5 plt.plot(x,y,
6 linewidth=1,
7 linestyle='--',
8 color='red',
9 marker='o',
10 markersize=15,
11 markeredgewidth=3,
12 markeredgecolor='blue',
13 markerfacecolor='black',
14 fillstyle='left')
NameError: name 'plt' is not defined
# Adding labels and titles
plt.plot(x,y)
plt.plot(x,x, 'r')
plt.xlabel('X Label')
plt.ylabel('Y Label')
plt.title('Title')
plt.legend(['ABCD', 'EFGH'], loc='best')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[10], line 2
1 # Adding labels and titles
----> 2 plt.plot(x,y)
3 plt.plot(x,x, 'r')
4 plt.xlabel('X Label')
NameError: name 'plt' is not defined
# Subplots -- have multiple plots
plt.subplot(1,2,1)
plt.plot(x,y)
plt.xlabel('X Label')
plt.ylabel('Y Label')
plt.title('Title')
plt.subplot(1,2,2)
plt.plot(x,y, '--r')
plt.xlabel('X Label')
plt.ylabel('Y Label')
plt.title('Title')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[11], line 2
1 # Subplots -- have multiple plots
----> 2 plt.subplot(1,2,1)
3 plt.plot(x,y)
4 plt.xlabel('X Label')
NameError: name 'plt' is not defined
# Subplots -- have multiple plots
plt.subplot(2,2,1)
plt.plot(x,y)
plt.xlabel('X Label')
plt.ylabel('Y Label')
plt.title('1')
plt.subplot(2,2,2)
plt.plot(x,y, 'r')
plt.xlabel('X Label')
plt.ylabel('Y Label')
plt.title('2')
plt.subplot(2,2,3)
plt.plot(x,y)
plt.xlabel('X Label')
plt.ylabel('Y Label')
plt.title('3')
plt.subplot(2,2,4)
plt.plot(x,y, 'r')
plt.xlabel('X Label')
plt.ylabel('Y Label')
plt.title('4')
plt.tight_layout()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[12], line 2
1 # Subplots -- have multiple plots
----> 2 plt.subplot(2,2,1)
3 plt.plot(x,y)
4 plt.xlabel('X Label')
NameError: name 'plt' is not defined
# Method 2 -- Object Oriented way
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 1])
# rect : sequence of float
# The dimensions [left, bottom, width, height] of the new axes.
# All quantities are in fractions of figure width and height.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[13], line 2
1 # Method 2 -- Object Oriented way
----> 2 fig = plt.figure()
4 axes = fig.add_axes([0.1, 0.1, 0.8, 1])
5 # rect : sequence of float
6 # The dimensions [left, bottom, width, height] of the new axes.
7 # All quantities are in fractions of figure width and height.
NameError: name 'plt' is not defined
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.5, 1])
# rect : sequence of float
# The dimensions [left, bottom, width, height] of the new axes.
# All quantities are in fractions of figure width and height.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[14], line 1
----> 1 fig = plt.figure()
3 axes = fig.add_axes([0.1, 0.1, 0.5, 1])
4 # rect : sequence of float
5 # The dimensions [left, bottom, width, height] of the new axes.
6 # All quantities are in fractions of figure width and height.
NameError: name 'plt' is not defined
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 1, 1])
# rect : sequence of float
# The dimensions [left, bottom, width, height] of the new axes.
# All quantities are in fractions of figure width and height.
axes.plot(x,y)
axes.set_xlabel('X Label')
axes.set_ylabel('Y Label')
axes.set_title('Title')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[15], line 1
----> 1 fig = plt.figure()
3 axes = fig.add_axes([0.1, 0.1, 1, 1])
4 # rect : sequence of float
5 # The dimensions [left, bottom, width, height] of the new axes.
6 # All quantities are in fractions of figure width and height.
NameError: name 'plt' is not defined
fig = plt.figure()
axes1 = fig.add_axes([0, 0, 1, 1])
axes2 = fig.add_axes([0.5, 0.1, 1, 1])
# rect : sequence of float
# The dimensions [left, bottom, width, height] of the new axes.
# All quantities are in fractions of figure width and height.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[16], line 1
----> 1 fig = plt.figure()
3 axes1 = fig.add_axes([0, 0, 1, 1])
4 axes2 = fig.add_axes([0.5, 0.1, 1, 1])
NameError: name 'plt' is not defined
fig = plt.figure()
axes1 = fig.add_axes([0, 0, 1, 1])
axes2 = fig.add_axes([0.12, 0.45, 0.45, 0.45])
# rect : sequence of float
# The dimensions [left, bottom, width, height] of the new axes.
# All quantities are in fractions of figure width and height.
axes1.plot(x,y)
axes1.set_xlabel('X Label')
axes1.set_ylabel('Y Label')
axes1.set_title('Larger Plot')
axes2.plot(x,y, 'ro')
axes2.set_xlabel('X Label')
axes2.set_ylabel('Y Label')
axes2.set_title('Smaller Plot')
axes3 = fig.add_axes([0.8, 0.2, 0.25, 0.25])
axes3.plot(x,y, 'y--')
axes3.set_xlabel('X Label')
axes3.set_ylabel('Y Label')
axes3.set_title('Smallest Plot')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[17], line 1
----> 1 fig = plt.figure()
3 axes1 = fig.add_axes([0, 0, 1, 1])
4 axes2 = fig.add_axes([0.12, 0.45, 0.45, 0.45])
NameError: name 'plt' is not defined
y
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
fig, axes = plt.subplots(nrows=2, ncols=2)
plt.tight_layout()
axes
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[19], line 1
----> 1 fig, axes = plt.subplots(nrows=2, ncols=2)
2 plt.tight_layout()
3 axes
NameError: name 'plt' is not defined
print(axes)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[20], line 1
----> 1 print(axes)
NameError: name 'axes' is not defined
type(axes)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[21], line 1
----> 1 type(axes)
NameError: name 'axes' is not defined
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0][0].plot(x,y)
plt.tight_layout()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[22], line 1
----> 1 fig, axes = plt.subplots(nrows=2, ncols=2)
4 axes[0][0].plot(x,y)
5 plt.tight_layout()
NameError: name 'plt' is not defined
fig, axes = plt.subplots(nrows=2, ncols=2)
line_styles = ['', '--', '-', '-.', ':']
colors = ['', 'b', 'g', 'k', 'y']
for idx, ax in enumerate(axes.reshape(-1), 1):
ax.plot(x,y, color=colors[idx], linestyle=line_styles[idx])
ax.set_title(f'This is plot # {idx}.')
plt.tight_layout()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[23], line 1
----> 1 fig, axes = plt.subplots(nrows=2, ncols=2)
3 line_styles = ['', '--', '-', '-.', ':']
4 colors = ['', 'b', 'g', 'k', 'y']
NameError: name 'plt' is not defined
axes[0][0]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[24], line 1
----> 1 axes[0][0]
NameError: name 'axes' is not defined
axes.reshape(-1)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[25], line 1
----> 1 axes.reshape(-1)
NameError: name 'axes' is not defined
fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(16,5))
axes[0].plot(x,y)
axes[1].plot(x,y, 'ro')
plt.tight_layout()
# figsize : (float, float), optional, default: None
# width, height in inches. If not provided, defaults to [6.4, 4.8]
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[26], line 1
----> 1 fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(16,5))
2 axes[0].plot(x,y)
3 axes[1].plot(x,y, 'ro')
NameError: name 'plt' is not defined
# fig.savefig('figure') #default is png
# fig.savefig('figure.jpeg')
# fig.savefig('figure2', dpi=300)
fig.savefig('figure2svg.svg', dpi=300)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[27], line 4
1 # fig.savefig('figure') #default is png
2 # fig.savefig('figure.jpeg')
3 # fig.savefig('figure2', dpi=300)
----> 4 fig.savefig('figure2svg.svg', dpi=300)
NameError: name 'fig' is not defined
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 1, 1])
# rect : sequence of float
# The dimensions [left, bottom, width, height] of the new axes.
# All quantities are in fractions of figure width and height.
y3 = [ele*3 for ele in y]
axes.plot(x,y, label='x,y')
axes.plot(x,y3, label='x,y**3')
axes.set_xlabel('X Label')
axes.set_ylabel('Y Label')
axes.set_title('Title')
axes.legend(loc='lower right', fontsize=24)
# axes.legend(loc=1)
axes.legend(loc=[0.5,0.5])
# Location String Location Code
# 'best' 0
# 'upper right' 1
# 'upper left' 2
# 'lower left' 3
# 'lower right' 4
# 'right' 5
# 'center left' 6
# 'center right' 7
# 'lower center' 8
# 'upper center' 9
# 'center' 10
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[28], line 1
----> 1 fig = plt.figure()
3 axes = fig.add_axes([0.1, 0.1, 1, 1])
4 # rect : sequence of float
5 # The dimensions [left, bottom, width, height] of the new axes.
6 # All quantities are in fractions of figure width and height.
NameError: name 'plt' is not defined
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 1, 1])
# axes.plot(x,y, 'r')
# axes.plot(x,y, color='yellow')
# axes.plot(x,y, 'k')
# axes.plot(x,y, color='black')
# # https://www.color-hex.com/
axes.plot(x,y, color='#F75D5D', linewidth=10)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[29], line 1
----> 1 fig = plt.figure()
3 axes = fig.add_axes([0.1, 0.1, 1, 1])
4 # axes.plot(x,y, 'r')
5 # axes.plot(x,y, color='yellow')
6
(...) 9
10 # # https://www.color-hex.com/
NameError: name 'plt' is not defined
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 1, 1])
# axes.plot(x,y, 'r', linewidth=4)
axes.plot(x,y, 'o--b', lw=4, alpha=0.1, ms=20)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[30], line 1
----> 1 fig = plt.figure()
3 axes = fig.add_axes([0.1, 0.1, 1, 1])
4 # axes.plot(x,y, 'r', linewidth=4)
NameError: name 'plt' is not defined
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 1, 1])
axes.plot(x,y, 'r-.', lw=5, linestyle=':')
# Linestyle Description
# '-' or 'solid' solid line
# '--' or 'dashed' dashed line
# '-.' or 'dashdot' dash-dotted line
# ':' or 'dotted' dotted line
# 'None' or ' ' or '' draw nothing
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[31], line 1
----> 1 fig = plt.figure()
3 axes = fig.add_axes([0.1, 0.1, 1, 1])
4 axes.plot(x,y, 'r-.', lw=5, linestyle=':')
NameError: name 'plt' is not defined
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 1, 1])
# axes.plot(x,y, marker='o')
axes.plot(x,y, ' b', marker='^', markersize=10)
#https://matplotlib.org/3.1.1/api/markers_api.html
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[32], line 1
----> 1 fig = plt.figure()
3 axes = fig.add_axes([0.1, 0.1, 1, 1])
4 # axes.plot(x,y, marker='o')
NameError: name 'plt' is not defined
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 1, 1])
# axes.plot(x,y, 'b', marker='o', markersize=10, markerfacecolor='red')
axes.plot(x,y, 'b', marker='o', markersize=30, markerfacecolor='yellow', markeredgewidth=3, markeredgecolor='k')
#https://matplotlib.org/3.1.1/api/markers_api.html
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[33], line 1
----> 1 fig = plt.figure()
3 axes = fig.add_axes([0.1, 0.1, 1, 1])
4 # axes.plot(x,y, 'b', marker='o', markersize=10, markerfacecolor='red')
NameError: name 'plt' is not defined
fig = plt.figure()
axes = fig.add_axes([0, 0, 1, 1])
axes.plot(x,y)
axes.set_xlim([0,5])
axes.set_ylim([0,30])
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[34], line 1
----> 1 fig = plt.figure()
3 axes = fig.add_axes([0, 0, 1, 1])
4 axes.plot(x,y)
NameError: name 'plt' is not defined
# https://github.com/rougier/matplotlib-tutorial
# https://medium.com/@kapil.mathur1987/matplotlib-an-introduction-to-its-object-oriented-interface-a318b1530aed
import numpy as np
t = 2*np.pi/3
plt.plot([t,t],[0,np.cos(t)], color ='blue', linewidth=1.5, linestyle="--")
plt.scatter([t,],[np.cos(t),], 50, color ='blue')
plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plt.plot([t,t],[0,np.sin(t)], color ='red', linewidth=1.5, linestyle="--")
plt.scatter([t,],[np.sin(t),], 50, color ='red')
plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[36], line 1
----> 1 import numpy as np
3 t = 2*np.pi/3
4 plt.plot([t,t],[0,np.cos(t)], color ='blue', linewidth=1.5, linestyle="--")
ModuleNotFoundError: No module named 'numpy'
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
data = pd.read_csv("https://raw.githubusercontent.com/fivethirtyeight/data/master/airline-safety/airline-safety.csv")
# Get figure object and an array of axes objects
fig, arr_ax = plt.subplots(2, 2)
display(data)
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[37], line 1
----> 1 import matplotlib.pyplot as plt
2 import pandas as pd
3 import numpy as np
ModuleNotFoundError: No module named 'matplotlib'
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
data = pd.read_csv("https://raw.githubusercontent.com/fivethirtyeight/data/master/airline-safety/airline-safety.csv")
# Get figure object and an array of axes objects
fig, arr_ax = plt.subplots(2, 2)
# arr_ax[x][x] or arr_ax[x,x]
# Histogram - fatal_accidents_85_99
arr_ax[0,0].hist(data['fatal_accidents_85_99'])
arr_ax[0,0].set_title('fatal_accidents_85_99')
# Histogram - fatal_accidents_00_14
arr_ax[0,1].hist(data['fatal_accidents_00_14'])
arr_ax[0,1].set_title('fatal_accidents_00_14')
# Scatter - fatal_accidents_85_99 vs fatalities_85_99
arr_ax[1,0].scatter(data['fatal_accidents_85_99'], data['fatalities_85_99'])
arr_ax[1,0].set_xlabel('fatal_accidents_85_99')
arr_ax[1,0].set_ylabel('fatalities_85_99')
# scatter - avail_seat_km_per_week vs fatalities_00_14
arr_ax[1,1].scatter(data['avail_seat_km_per_week'], data['fatalities_00_14'])
arr_ax[1,1].set_xlabel('avail_seat_km_per_week')
arr_ax[1,1].set_ylabel('fatalities_00_14')
plt.tight_layout()
plt.show()
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[38], line 1
----> 1 import matplotlib.pyplot as plt
2 import pandas as pd
3 import numpy as np
ModuleNotFoundError: No module named 'matplotlib'
# https://www.machinelearningplus.com/plots/top-50-matplotlib-visualizations-the-master-plots-python/
# https://levelup.gitconnected.com/an-introduction-of-python-matplotlib-with-40-basic-examples-5174383a6889
import pandas as pd
import numpy as np
# Prepare Data
df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mtcars.csv")
x = df.loc[:, ['mpg']]
df['mpg_z'] = (x - x.mean())/x.std()
df['colors'] = ['red' if x < 0 else 'darkgreen' for x in df['mpg_z']]
df.sort_values('mpg_z', inplace=True)
df.reset_index(inplace=True)
# Draw plot
plt.figure(figsize=(14,16), dpi= 80)
plt.scatter(df.mpg_z, df.index, s=450, alpha=.6, color=df.colors)
for x, y, tex in zip(df.mpg_z, df.index, df.mpg_z):
t = plt.text(x, y, round(tex, 1), horizontalalignment='center',
verticalalignment='center', fontdict={'color':'white'})
# Decorations
# Lighten borders
plt.gca().spines["top"].set_alpha(.3)
plt.gca().spines["bottom"].set_alpha(.3)
plt.gca().spines["right"].set_alpha(.3)
plt.gca().spines["left"].set_alpha(.3)
plt.yticks(df.index, df.cars)
plt.title('Diverging Dotplot of Car Mileage', fontdict={'size':20})
plt.xlabel('$Mileage$')
plt.grid(linestyle='--', alpha=0.5)
plt.xlim(-2.5, 2.5)
plt.show()
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[40], line 1
----> 1 import pandas as pd
2 import numpy as np
3 # Prepare Data
ModuleNotFoundError: No module named 'pandas'
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
freqs = np.arange(2, 20, 3)
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
t = np.arange(0.0, 1.0, 0.001)
s = np.sin(2*np.pi*freqs[0]*t)
l, = ax.plot(t, s, lw=2)
class Index:
ind = 0
def next(self, event):
self.ind += 1
i = self.ind % len(freqs)
ydata = np.sin(2*np.pi*freqs[i]*t)
l.set_ydata(ydata)
plt.draw()
def prev(self, event):
self.ind -= 1
i = self.ind % len(freqs)
ydata = np.sin(2*np.pi*freqs[i]*t)
l.set_ydata(ydata)
plt.draw()
callback = Index()
axprev = fig.add_axes([0.7, 0.05, 0.1, 0.075])
axnext = fig.add_axes([0.81, 0.05, 0.1, 0.075])
bnext = Button(axnext, 'Next')
bnext.on_clicked(callback.next)
bprev = Button(axprev, 'Previous')
bprev.on_clicked(callback.prev)
plt.show()
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[41], line 1
----> 1 import numpy as np
2 import matplotlib.pyplot as plt
3 from matplotlib.widgets import Button
ModuleNotFoundError: No module named 'numpy'