【莫烦Python】Nnmpy & Pandas: https://www.bilibili.com/video/BV1Ex411L7oT 【莫烦Python】Matplotlib Python 画图教程: https://www.bilibili.com/video/BV1Jx411L7LU Numpy 官网文档:https://www.numpy.org.cn/user/setting-up.html Pandas 官网文档:https://www.pypandas.cn/docs/ Matplotlib 官网文档:https://www.matplotlib.org.cn/tutorials/
目录
- Numpy 介绍
- Numpy 基本属性: ndim, shape, size, dtype
- Numpy 创建矩阵: zeros, ones, empty, arange, linspace, random
- Numpy 计算: + - * / **, sin, dot, sum, max, min, mean, median, cumsum, diff, nonzero, sort, argmax, T, transpose, clip, flat
- Numpy 合并与分割: vstack, hstack, concatenate, split, array_split, vsplit, hsplit
- Numpy 拷贝: copy
- Pandas 介绍
- Pandas 多种创建方式: Series, DataFrame, date_range
- Pandas 常用属性和访问操作: dtypes, index, columns, values, describe, T, sort_index, sort_values
- Pandas 数据切片: loc, iloc
- Pandas 赋值,添加新列
- Pandas 处理缺失数据 NaN: isna, isnull, fillna, dropna
- Pandas 处理文件
- Pandas 合并: concat append
- Pandas 合并 merge
- Pandas 画图
- Matplotlib 基本使用
- Matplotlib Figure
- Matplotlib 坐标轴设置
- Matplotlib 图例 legend
- Matplotlib 添加注解
- Matplotlib 坐标轴的标签防遮挡
- Matplotlib 散点图
- Matplotlib 柱状图
- Matplotlib 等高线图
- Matplotlib 图片
- Matplotlib 3D图形
- Matplotlib 一个窗口显示多张子图 Subplot
- Matplotlib 多子图:subplot2grid、girdspec
- Matplotlib 图中图
- Matplotlib 主次坐标轴
- Matplotlib 动画 Animation
Numpy 介绍
- numpy 是基于C语言,对大量数据计算,快
- pandas 基于 numpy 再封装
Numpy 基本属性: ndim, shape, size, dtype
import numpy as np
array = np.array([[1, 2, 3],
[3, 4, 5]])
print(array)
print(f'number of dim: {array.ndim}')
print(f'shape: {array.shape}')
print(f'size: {array.size}')
Numpy 创建矩阵: zeros, ones, empty, arange, linspace, random
array = np.array([[1, 2, 3], [3, 4, 5]], dtype=np.int16)
print(f'type: {array.dtype}')
array = np.zeros([2, 3, 4])
print(array)
array = np.ones([1, 2, 3], dtype=np.int0)
print(array, array.dtype)
array = np.empty([1, 2, 3,4])
print(array)
array = np.arange(10, 20, 2)
print(array)
array = np.arange(12).reshape((3, 4))
print(array)
array = np.linspace(1, 10, 3)
print(array)
array = np.random.random((2, 4))
print(array)
Numpy 计算: + - * / **, sin, dot, sum, max, min, mean, median, cumsum, diff, nonzero, sort, argmax, T, transpose, clip, flat
import numpy as np
a = np.array([[1, 1], [0, 1]])
b = np.arange(4).reshape((2, 2))
c = a - b
print(c)
c = 10 * np.sin(a)
print(c)
print(b < 3)
c = np.dot(a, b)
c = a.dot(b)
print(c)
print(np.sum(a))
print(np.max(a))
print(np.min(a))
a = np.array([[1, 2], [3, 4]])
print(np.sum(a, axis=0))
print(np.sum(a, axis=1))
print(np.max(a, axis=0))
print(np.max(a, axis=1))
print(np.min(a, axis=0))
print(np.min(a, axis=1))
print(np.mean(a))
print(a.mean())
print(np.median(a))
print(np.cumsum(a))
print(np.diff(a))
print(np.nonzero(a))
print(np.sort(a))
print(np.argmax(a))
print(np.transpose(a))
print(a.T)
print(np.clip(a, 1, 1))
a = np.arange(3, 15)
print(a)
print(a[2])
a = a.reshape((3, 4))
print(a)
print(a[2])
print(a[0][2])
print(a[0, 2])
print(a[0, :])
for row in a:
print(row)
for col in a.T:
print(col)
for item in a.flat:
print(item)
print(a.flatten())
Numpy 合并与分割: vstack, hstack, concatenate, split, array_split, vsplit, hsplit
import numpy as np
a = np.array([1, 1, 1])
b = np.array([2, 2, 2])
print(np.vstack((a, b)))
print(a.shape, np.vstack((a, b)).shape)
print(np.hstack((a, b)))
print(a[:, np.newaxis])
print(np.vstack(a))
print(a.reshape(a.size, 1))
print(a[np.newaxis, :])
a = a[np.newaxis, :]
b = b[np.newaxis, :]
print(a, b)
c = np.concatenate((a, b), axis=0)
print(c)
c = np.concatenate((a, b), axis=1)
print(c)
a = np.arange(12).reshape((3, 4))
print(a)
print(np.split(a, 2, axis=1))
print(np.array_split(a, 3, axis=1))
print(np.array_split(a, (1, 2, 1), axis=1))
print(np.vsplit(a, 3))
print(np.hsplit(a, 2))
Numpy 拷贝: copy
import numpy as np
a = np.arange(4)
b = a
print(b is a)
b = a.copy()
Pandas 介绍
- numpy是array是多维list
- pandas是字典,每一行和列可以自定义命名
- nan : no a mumber
Pandas 多种创建方式: Series, DataFrame, date_range
import numpy as np
import pandas as pd
s = pd.Series([1, 3, 6, np.nan, 44, 1])
print(s)
df = pd.DataFrame(np.arange(12).reshape((3, 4)))
print(df)
dates = pd.date_range('20211201', periods=6)
print(dates)
df = pd.DataFrame(np.random.rand(6, 4), index=dates,
columns=['a', 'b', 'c', 'd'])
print(df)
df = pd.DataFrame({
'A': 1,
'B': pd.Timestamp('20211201'),
'C': pd.Series(1., index=list(range(4)), dtype='float64'),
'D': np.array([3] * 4, dtype='int64'),
'E': pd.Categorical(['test', 'train', 'test', 'train']),
'F': 'foo'
})
print(df)
Pandas 常用属性和访问操作: dtypes, index, columns, values, describe, T, sort_index, sort_values
import numpy as np
import pandas as pd
df = = pd.DataFrame({
'A': 1,
'B': pd.Timestamp('20211201'),
'C': pd.Series(1., index=list(range(4)), dtype='float64'),
'D': np.array([3] * 4, dtype='int64'),
'E': pd.Categorical(['test', 'train', 'test', 'train']),
'F': 'foo'
})
print(df.dtypes)
print(df.index)
print(df.columns)
print(df.values, type(df.values))
print(df.describe())
print(df.T)
print(df.sort_index(axis=1, ascending=False))
print(df.sort_index(axis=0, ascending=False))
print(df.sort_values(by='E'))
Pandas 数据切片: loc, iloc
import numpy as np
import pandas as pd
dates = pd.date_range('20211201', periods=6)
df = pd.DataFrame(np.arange(24).reshape((6, 4)),
index=dates, columns=['A', 'B', 'C', 'D'])
print(df)
print(df['A'])
print(df.A)
print(df[0:3])
print(df['20211201':'20211203'])
print(df.loc['20211201'])
print(df.loc[:, ['A', 'B']])
print(df.loc['20211202':, ['A', 'B']])
print(df.iloc[3:5, 1:3])
print(df.iloc[[1, 3, 5], 1:3])
print(df[df.A > 8])
Pandas 赋值,添加新列
import numpy as np
import pandas as pd
dates = pd.date_range('20211201', periods=6)
df = pd.DataFrame(np.arange(24).reshape((6, 4)),
index=dates, columns=['A', 'B', 'C', 'D'])
print(df)
print(df.iloc[2, 2])
df.iloc[2, 2] = 111
print(df.iloc[2, 2])
print(df.loc['20211203', 'C'])
df.loc['20211203', 'C'] = 222
print(df.loc['20211203', 'C'])
df.B[df.A > 8] = 0
print(df)
df[df.A < 8] = 0
print(df)
df['F'] = np.nan
print(df)
df['D'] = pd.Series([1, 2, 3, 4, 5, 6], index=pd.date_range('20211201', periods=6))
print(df)
df['D'] = list(range(6, 12))
print(df)
Pandas 处理缺失数据 NaN: isna, isnull, fillna, dropna
import numpy as np
import pandas as pd
dates = pd.date_range('20211201', periods=6)
df = pd.DataFrame(np.arange(24).reshape((6, 4)),
index=dates, columns=['A', 'B', 'C', 'D'])
df.iloc[1, 1], df.iloc[2, 2] = np.nan, np.nan
print(df)
print(df.isnull())
print(np.any(df.isnull() == True))
print(np.any(df.isnull() is True))
print(np.any(df.isnull()))
print(df.fillna(value=99))
df.iloc[1, 1], df.iloc[2, 2] = np.nan, np.nan
print(df.dropna(axis=0, how='any'))
Pandas 处理文件
支持的文件: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html
import pandas as pd
csv_file = './test.csv'
writer = open(csv_file, 'w+', encoding='utf-8')
writer.write('id,name,num\n')
for i in range(10):
writer.write(f'{i},{i},{i}\n')
writer.close()
data = pd.read_csv(csv_file)
print(data)
data.to_pickle('./test.pickel')
data_pickel = pd.read_pickle('./test.pickel')
print(data_pickel)
Pandas 合并: concat append
import numpy as np
import pandas as pd
from pandas.io.spss import read_spss
df1 = pd.DataFrame(np.ones((3, 4)) * 0, columns=['a', 'b', 'c', 'd'])
df2 = pd.DataFrame(np.ones((3, 4)) * 1, columns=['a', 'b', 'c', 'd'])
df3 = pd.DataFrame(np.ones((3, 4)) * 2, columns=['a', 'b', 'c', 'd'])
print(df1)
print(df2)
print(df3)
res = pd.concat([df1, df2, df3], axis=0, ignore_index=True)
print(res)
df4 = pd.DataFrame(np.ones((3, 4))*0, index=[1, 2, 3], columns=['a', 'b', 'c', 'd'])
df5 = pd.DataFrame(np.ones((3, 4))*1, index=[2, 3, 4], columns=['b', 'c', 'd', 'e'])
print(df4)
print(df5)
res = pd.concat([df4, df5])
print(res)
res = pd.concat([df4, df5], axis=1)
print(res)
res = pd.concat([df4, df5], join='inner')
print(res)
res = df1.append([df2, df3], ignore_index=True)
print(res)
s1 = pd.Series(np.arange(4), index=['a', 'b', 'c', 'd'])
print(s1)
print(df1.append(s1, ignore_index=True))
Pandas 合并 merge
import pandas as pd
left = pd.DataFrame({
'key': ['K0', 'K1', 'K3', 'K4'],
'A': ['A0', 'A1', 'A3', 'A4'],
'B': ['B0', 'B1', 'B3', 'B4']
})
right = pd.DataFrame({
'key': ['K0', 'K1', 'K3', 'K4'],
'C': ['C0', 'C1', 'C3', 'C4'],
'D': ['D0', 'D1', 'D3', 'D4']
})
print(left)
print(right)
res = pd.merge(left, right, on='key')
print(res)
left = pd.DataFrame({
'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'A': ['A0', 'A1', 'A3', 'A4'],
'B': ['B0', 'B1', 'B3', 'B4']
})
right = pd.DataFrame({
'key1': ['K0', 'K1', 'K1', 'K2'],
'key2': ['K0', 'K0', 'K0', 'K0'],
'C': ['C0', 'C1', 'C3', 'C4'],
'D': ['D0', 'D1', 'D3', 'D4']
})
print(left)
print(right)
res = pd.merge(left, right, on=['key1', 'key2'])
print(res)
res = pd.merge(left, right, on=['key1', 'key2'], how='outer')
print(res)
res = pd.merge(left, right, on=['key1', 'key2'], how='left')
print(res)
res = pd.merge(left, right, on=['key1', 'key2'], how='right')
print(res)
res = pd.merge(left, right, on=['key1', 'key2'], how='right', indicator=True)
print(res)
res = pd.merge(left, right, on=['key1', 'key2'], how='right', indicator='tset-name')
print(res)
left = pd.DataFrame({
'A': ['A0', 'A1', 'A2'],
'B': ['B0', 'B1', 'B2']
}, index=['K0', 'K1', 'K2'])
right = pd.DataFrame({
'C': ['C0', 'C1', 'C3'],
'D': ['D0', 'D1', 'D3']
}, index=['K0', 'K2', 'K3'])
print(left)
print(right)
res = pd.merge(left, right, left_index=True, right_index=True, how='outer')
print(res)
res = pd.merge(left, right, left_index=True, right_index=True, how='inner')
print(res)
import pandas as pd
boys = pd.DataFrame({'k': ['K0', 'K1', 'K2'], 'age': [1, 2, 3], 'test_1': [1, 2, 2]})
girls = pd.DataFrame({'k': ['K0', 'K0', 'K3'], 'age': [4, 5, 3], 'test_2': [2, 2, 2]})
print(boys)
print(girls)
res = pd.merge(boys, girls, on='k', suffixes=['_boy', '_girls'], how='outer')
print(res)
Pandas 画图
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = pd.Series(np.random.randn(1000), index=np.arange(1000))
data = data.cumsum()
data.plot()
plt.show()
data = pd.DataFrame(np.random.randn(1000, 4), index=np.arange(1000), columns=list('ABDC'))
data = data.cumsum()
print(data.head(5))
data.plot()
plt.show()
pic = data.plot.scatter(x='A', y='B', color='DarkBlue', label='calss 1')
data.plot.scatter(x='A', y='C', color='DarkGreen', label='class 2', ax=pic)
data.plot()
plt.show()
Matplotlib 基本使用
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
y = x * 2 + 1
plt.plot(x, y)
plt.show()
Matplotlib Figure
- 默认是显示在一个figure上,可以手动创建,设置大小、名字
- 多个figure时,当前figure的属性设置代码直到遇到创建下一个figure
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = x * 2 + 1
y2 = x ** 2
plt.figure()
plt.plot(x, y1)
plt.figure('pic', figsize=(8, 5))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=3, linestyle='--')
plt.show()
Matplotlib 坐标轴设置
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = x * 2 + 1
y2 = x ** 2
plt.plot(x, y1, color='red', linewidth=3, linestyle='--')
plt.plot(x, y2)
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('x label')
plt.ylabel('y label')
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks(
[-2, -1.8, -1, 1.22, 3],
['really bad', 'bad', 'normal', 'good', 'really good']
)
plt.yticks(
[-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad\ \alpha$', r'$normal$', r'$good$', r'$really\ good$']
)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', -1))
ax.spines['left'].set_position(('data', 0))
plt.show()
Matplotlib 图例 legend
from logging import Handler
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = x * 2 + 1
y2 = x ** 2
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('x label')
plt.ylabel('y label')
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks(
[-2, -1.8, -1, 1.22, 3],
['really bad', 'bad', 'normal', 'good', 'really good']
)
plt.yticks(
[-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad\ \alpha$', r'$normal$', r'$good$', r'$really\ good$']
)
line1, = plt.plot(x, y1, color='red', linewidth=3, linestyle='--', label='up')
line2, = plt.plot(x, y2, label='down')
plt.legend(handles=[line1, line2, ], labels=['a', 'b'], loc='lower right')
plt.legend(handles=[line1,], labels=['a',], loc='lower right')
plt.show()
Matplotlib 添加注解
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = x * 2 + 1
plt.figure(num=1, figsize=(8, 5))
plt.plot(x, y)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
a = 1
b = a * 2 + 1
plt.scatter(a, b, s=50, color='b')
plt.plot([a, a], [b, 0], 'k--', lw=2.5)
plt.annotate(f'$2x+1={b}$', xy=(a, b), xycoords='data', xytext=(+30, -30), textcoords='offset points',
fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=.2'))
plt.text(-3, 3, r'$this\ is\ the\ text\ \sigma_i$', fontdict={'size': 16, 'color': 'r'})
plt.show()
Matplotlib 坐标轴的标签防遮挡
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = x * 0.1
plt.figure(num=1, figsize=(8, 5))
plt.plot(x, y, lw=10)
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
ax.xaxis.set_zorder(2)
ax.yaxis.set_zorder(2)
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7))
label.set_zorder(1)
plt.show()
Matplotlib 散点图
import matplotlib.pyplot as plt
import numpy as np
n = 1024
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
t = np.arctan2(y, x)
plt.scatter(x, y, s=75, c=t, alpha=0.5)
plt.xlim((-1.5, 1.5))
plt.ylim((-1.5, 1.5))
plt.xticks(())
plt.yticks(())
plt.show()
Matplotlib 柱状图
import matplotlib.pyplot as plt
import numpy as np
n = 12
x = np.arange(n)
y = (1 - x/float(n)) * np.random.uniform(0.5, 1.0, n)
plt.bar(x, y, facecolor='#9999ff', edgecolor='white')
plt.bar(x, -y, facecolor='#ff9999', edgecolor='white')
for xv, yv in zip(x, y):
plt.text(xv, yv+0.05, '%.2f' % yv, ha='center', va='bottom')
plt.text(xv, -yv-0.05, '%.2f' % -yv, ha='center', va='top')
plt.xlim(-0.5, n)
plt.ylim(-1.25, 1.25)
plt.xticks(())
plt.yticks(())
plt.show()
Matplotlib 等高线图
import matplotlib.pyplot as plt
import numpy as np
def getHeight(x, y):
return (1 - x/2 + x**5 + y**3) * np.exp(-x**2 - y**2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)
plt.contourf(X, Y, getHeight(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)
C = plt.contour(X, Y, getHeight(X, Y), 8, colors='black', linewidths=0.5)
plt.clabel(C, inline=True, fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show()
Matplotlib 图片
import matplotlib.pyplot as plt
import numpy as np
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
0.365348418405, 0.439599930621, 0.525083754405,
0.423733120134, 0.525083754405, 0.651536351379]).reshape(3, 3)
plt.imshow(a, interpolation='nearest', cmap='bone', origin='upper')
plt.colorbar(shrink=0.9)
plt.xticks(())
plt.yticks(())
plt.show()
Matplotlib 3D图形
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'), edgecolor='black')
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
ax.set_zlim(-2, 2)
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap='rainbow')
ax.contourf(X, Y, Z, zdir='x', offset=-4, cmap='rainbow')
ax.contourf(X, Y, Z, zdir='y', offset=4, cmap='rainbow')
plt.show()
Matplotlib 一个窗口显示多张子图 Subplot
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
plt.subplot(2, 1, 1)
plt.plot([0, 1], [0, 1])
plt.subplot(234)
plt.plot([0, 1], [0, 2])
plt.subplot(235)
plt.plot([0, 1], [0, 3])
plt.subplot(236)
plt.plot([0, 1], [0, 4])
plt.show()
Matplotlib 多子图:subplot2grid、girdspec
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as girdspec
plt.figure()
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
ax1.plot([1, 2], [1, 2])
ax1.set_title('subplot2grid')
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=1)
ax3 = plt.subplot2grid((3, 3), (1, 2), colspan=1, rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0), colspan=1, rowspan=1)
ax5 = plt.subplot2grid((3, 3), (2, 1), colspan=1, rowspan=1)
plt.figure()
gs = girdspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
ax1.set_title('girdspec')
plt.subplot(gs[1, :2])
plt.subplot(gs[1:, 2])
plt.subplot(gs[-1, 0])
plt.subplot(gs[-1, -2])
plt.show()
Matplotlib 图中图
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
x = np.arange(1, 8)
y = [1, 3, 4, 2, 5, 8, 6]
l, b, w, h = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([l, b, w, h])
ax1.plot(x, y, 'r')
l, b, w, h = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([l, b, w, h])
ax2.plot(x, y, 'b')
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(x, y[::-1], 'g')
plt.show()
Matplotlib 主次坐标轴
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 * y1
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'r--')
ax1.set_xlabel('x')
ax1.set_ylabel('y1')
ax2.set_ylabel('y2')
plt.show()
Matplotlib 动画 Animation
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
x = np.arange(0, 2*np.pi, 0.01)
fig, ax = plt.subplots()
line, = ax.plot(x, np.sin(x))
def animationFunc(i):
line.set_ydata(np.sin(x+i/10))
return line,
def initAnimationFunc():
line.set_ydata(np.sin(x))
return line,
ani = animation.FuncAnimation(fig=fig, func=animationFunc, frames=100, init_func=initAnimationFunc, interval=20, blit=False)
plt.show()
|