Matplotlib画图

2. Matplotlib画图

2.1. Matplotlib简介

2.1.1. 为什么要用Matplotlib

非常强大,可以画各种类型的图

2.1.2. 安装

pip3.9 install -i https://pypi.tuna.tsinghua.edu.cn/simple matplotlib

2.2. 基本使用

2.2.1. 基本用法

三步:figure, plot, show

x = np.linspace(-1, 1, 50)
y = 2*x + 1
plt.figure()
plt.plot(x, y)
plt.show()

2.2.2. figure 设置

设置figure的名称,大小等
plt.figure(num=3, figsize=(8, 5))

2.2.3. 坐标轴设置

设置坐标轴范围、名称、刻度
plt.xlim(-2, 2)
plt.xlabel(‘x label’)
plt.xticks([-1.5, -0.5, 2], [r’ a a a’, r’ b b b’, r’ α \alpha α’])

设置坐标轴的颜色、位置,刻度显示位置等
ax = plt.gca() # gca = ‘get current axis’
ax.spines[‘right’].set_color(‘none’)
ax.spines[‘left’].set_position((‘data’, 0))
ax.xaxis.set_ticks_position(‘top’)

2.2.4. 添加图例

注意逗号

l1, = plt.plot(x, y)
plt.legend(handles=[l1], labels=['line 1'], loc='upper right')

2.2.5. Annotation标注、text注释

当某些特殊地方需要标注时,可以使用annotation 或 text

x0 = 1.5
y0 = x0**2
plt.plot([x0, x0], [0, y0], linestyle='--')
plt.annotate(r'$x**2=%s$' % y0, xy=(x0, y0), xycoords='data',
             xytext=(+20, -20), textcoords='offset points', fontsize=10,
             arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=.2'))
plt.text(-1, 2, r'$aa\ \mu,\sigma_i$', fontdict={'size': 10, 'color': 'r'})

2.3. 画图种类

线图、散点图、柱状图、等高线图、image图片、3D数据

2.3.1. 散点图

# 平均数0,方差1
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(Y, X)
plt.scatter(X, Y, s=15, c=T, alpha=.5)

2.3.2. 柱状图

n = 12
X = np.arange(n)
Y = np.random.uniform(0.0, 1.0, n)
plt.bar(X, Y, facecolor='#9999ff', edgecolor='white', alpha=0.8)
for x, y in zip(X, Y):
	# ha: horizontal alignment
    plt.text(x, y, '%.2f' % y, ha='center', va='bottom')
plt.show()

2.3.3. 等高线图

数据集为:点(x,y)和对应的高度值

def f(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, f(X, Y), 10, alpha=.75, cmap=plt.cm.hot)
# 加等高线
C = plt.contour(X, Y, f(X, Y), 10, colors='black', linewidth=.5)
# 加高度数字
plt.clabel(C, inline=True, fontsize=10)
plt.show()

2.3.4. Image图片

2.3.5. 3D数据

需要引入3D模块

import numpy as np
import matplotlib.pyplot as plt
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)
ax.plot_surface(X, Y, X**2 + Y**2, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
ax.contourf(X, Y, X**2 + Y**2, zdir='z', offset=-1, cmap='rainbow')
plt.show()

2.4. 多合一显示

import numpy as np
import matplotlib.pyplot as plt
# from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(2, figsize=(5, 4))
ax1 = fig.add_subplot(211, projection='3d')
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
ax1.plot_surface(X, Y, X**2 + Y**2, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
ax1.contourf(X, Y, X**2 + Y**2, zdir='z', offset=-1, cmap='rainbow')
ax1.set_xlim([-5, 5])
ax1.set_ylim([-5, 5])

ax2 = fig.add_subplot(212)
ax2.plot([0, 1], [0, 1])

plt.show()

2.5. Animation动画

from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np

fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))


def animate(i):
    line.set_ydata(np.sin(x + i/100 * (2*np.pi)))
    return line,


def init():
    line.set_ydata(np.sin(x))
    return line,


ani = animation.FuncAnimation(fig=fig,
                              func=animate,
                              frames=100,
                              init_func=init,
                              interval=5,
                              blit=False)
# ani.save('test.gif')
plt.show()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值