Pyplot基础教程

Pyplot基础教程

matplotlib的pyplot子库提供了和matlab类似的绘图API

绘图基础

定义图像窗口

plt.figure()    # 定义一个图像窗口
plt.show()      # 显示图像

figure窗口

plt.figure(num=3, figsize=(8,5))    # 图像窗口,编号为3,大小为(8,5)
plt.plot(x,y,color='red',linewidth=1.0,linestyle='--')   #  设置线的颜色、宽度、类型

坐标轴

plt.xlim((-1,2))    # 设置x轴的范围
plt.ylim((-2,3))    # 设置y轴的范围
plt.xlabel('X') # 设置X坐标轴名称
plt.ylabel('Y') # 设置Y坐标轴名称
plt.xticks([1,2,3]) # 设置X轴的刻度
plt.yticks([1,2,3],['a','b','c'])   # 设置Y轴的刻度和名称

Legend图例

plt.plot(x, y1, label='liner line') # 线的信息
plt.plot(x, y2, label='square line')
plt.legend(loc='upper right')   # legend将显示的信息来自,代码中的label。
l1, = plt.plot(x, y1)   # 用变量保存两条线,因为返回的是列表,要用参数后面要加,
l2, = plt.plot(x, y2)
plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='best') # label设置线条名称,loc是标签位置,best自动分配最佳位置
x = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2
plt.figure()
l1, = plt.plot(x, y1)
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--')
plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='best')
plt.xlim((-1, 2))
plt.ylim((-2, 5))
plt.xlabel('X')
plt.ylabel('Y')
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1, 0, 1, 3], ['a', 'b', 'c', 'd', 'e'])
plt.show()

设置坐标轴信息

ax = plt.gca()  # 获取当前坐标轴信息
ax.spines['right].set_color('none') # 使用spines设置边框,右侧,set_color设置颜色,默认白色
ax.spines['top'].set_color('none')  # 设置上边框
ax.xaxis.set_ticks_position('bottom')   # 设置x坐标刻度数字或名称位置top、bottom、both、default、none
ax.spines['bottom'].set_position(('data', 0))   # 设置边框位置(属性outward、axes、data),y=0的位置

sin和cos

x = np.linspace(-np.pi, np.pi, 256, endpoint=True)  # 左闭右开,endpoint为真保留最后一个。
C, S = np.cos(x), np.sin(x)
plt.plot(x, C)
plt.plot(x, S)
plt.xlabel('x')
plt.ylabel('y')
plt.show()

指定绘图大小

指定图像编号和大小

plt.figure(1, figsize=(8, 6))

线的颜色、粗细和类型

plt.plot(x, C, color="blue", linewidth=4.0, linestyle="--", label="cos")

指定x坐标轴范围

plt.xlim(-4.0, 4.0)

设置y轴刻度间隔

plt.yticks(np.linspace(-1, 1, 15, endpoint=True))

图例位置

显示plot中的参数label

plt.legend(loc='upper left')

画多个图

代表图像共有几行,几列,和图的位置。如231将图分为6个位置,1代表第一个位置。

plt.subplot(1, 2, 1)

散点图

plt.scatter(x,y)

条形图

填充颜色为facecolor,边界颜色为edgecolor

plt.bar(X, Y, facecolor="red", edgecolor="blue" )

饼线图

传入一个序列

plt.figure(figsize=(8,8))
n = 20
Z = np.arange(10)
plt.pie(Z)
plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值