Python3 - matplotlib: subplot, plot, figure, add_axes

使用matplotlib可以显示各种各样的图表

import numpy as np
import matplotlib.pyplot as plt

# Matplotlib is the most popular plotting library for Python
# It gives you control over every aspect of a figure
# It was designed to have a similar feel to MatLab's graphical plotting

x = np.linspace(0,5,11)
y = x ** 2
print("x: " , x)
print("y: ", y)
print('\n')

print("*** Show the Plot ***")
plt.plot(x,y)
plt.show()

结果如下:
在这里插入图片描述
在这里插入图片描述
要想改变图中线的颜色,可以这样改:
代码是紧跟着

plt.plot(x,y, 'r-')
plt.show()

效果如下:
在这里插入图片描述
要想给横纵坐标和图表写上名称,可以这么做:

plt.plot(x,y, 'r-')
plt.xlabel('X Label')
plt.ylabel('Y Label')
plt.title('Add Label')
plt.show()

结果如下:
在这里插入图片描述
使用subplot 来分区:

#subplot(numRows, numCols, plotNum)
# 图表的整个绘图区域被分成numRows 行 和 numCols 列
# 按照从左往右,从上到下的顺序对每个子区域进行编号,左上的子区域的编号为1
# plotNum 参数指定的子图对象所在的区域

plt.subplot(1,1,1) # 绘制 1 x 1 的图片区域
plt.plot(x,y,'r')
plt.show()

plt.subplot(2,1,2) # 绘制 2 x 1 的图片区域
plt.plot(y,x,'g')
plt.show()

结果如下:
在这里插入图片描述
在这里插入图片描述
使用Jupyter 来做练习

x = np.linspace(0,5,11)
y = x ** 2

plt.subplot(1,2,1) 
plt.plot(x,y,'r')

plt.subplot(1,2,2) 
plt.plot(y,x,'g')
plt.show()

在这里插入图片描述

使用figure(), add_axes() 来调整图片位置

x = np.linspace(0,5,11)
y = x ** 2

fig = plt.figure()
axes = fig.add_axes([0.1,0.1,0.8,0.8]) # 分别对应:left, bottom, width, height
axes.plot(x,y)
axes.set_title('area1')

axes_new = fig.add_axes([0.2,0.5,0.3,0.3]) # 分别对应: left, bottom, width, height
axes_new.plot(x,y,'g')
axes_new.set_title('area2')
plt.show()

结果如下:
在这里插入图片描述
如果觉得不错,就点赞或者关注或者留言~~
谢谢各位~ ~

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值