python使用matplotlib画图

【README】

plot画图有两种方法:包括 plt.plot(), ax.plot()-画多个子图 ,其中ax表示某个坐标轴;


【1】画单个图

python 复制代码
import matplotlib
# 避免兼容性问题:明确指定 matplotlib 使用兼容的后端,TkAgg 或 Agg
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np

# 设置画布大小(宽=8个单位,高=4个单位)
figure01 = plt.figure(figsize=(8, 4))

# plot画图有两种方法:包括 plt.plot(), ax.plot()-画多个子图 ,其中ax表示某个坐标轴

X = np.arange(0, 12.1, 0.1)
Y = np.sin(X)
# 画线
# marker 画点
# linestyle 设置为空串,plt.plot()画出来的是散点图
# zorder 设置图像上下层(数值越大,在上层)
plt.plot(X, Y, color='lime', linestyle='-.', linewidth=2,
         marker='^', markerfacecolor='black', markeredgecolor='red', markersize=3, markeredgewidth=1, label='Normal',  zorder=2)

# 获取坐标轴
ax1 = plt.gca()
ax1.set_title('Git Title', fontname='Times New Roman', fontsize='20', weight='bold', style='italic')
ax1.set_xlabel('X Label-time(UTC)')
ax1.set_ylabel('T($^o$C)')

# 设置刻度
ax1.set_xticks(np.arange(0, 12, 1.5))
# 设置刻度属性,如方向,颜色
ax1.tick_params(axis='both', direction='in', colors='blue', length=10, width=1)

# 画多个图
plt.plot(X+2, Y, label='Strange', zorder=1)

# plt.plot() 设置多个图的label标签,然后调用plt.legend()显式图例标签
plt.legend()

# 画图紧致布局
plt.tight_layout()
# 保存
plt.savefig('./matplotlib_exercise01.png', dpi=400)

plt.show()

# 画散点图
# plt.scatter(X, Y)
# # plt.show()

结果:


【2】一个面板画多个图

python 复制代码
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np

# plot画子图
X = np.arange(0, 12.1, 0.1)
Y = np.sin(X)

# 获取多个子图的图像与坐标轴
# figure表示画布, ax_array表示坐标轴数组
figure, ax_array = plt.subplots(nrows=2, ncols=2)
print("type(figure) = ", type(figure))
print("type(ax_array) = ", type(ax_array))
# type(figure) =  <class 'matplotlib.figure.Figure'>
# type(ax_array) =  <class 'numpy.ndarray'>

ax_array[0, 0].plot(X, Y)
ax_array[0, 1].plot(X, Y + 1)
ax_array[1, 0].plot(X + 1, Y)
ax_array[1, 1].plot(X, Y + 1)


# 设置x轴的取值范围相同,以便比较
ax_array[0, 0].set_xlim([0, 10])
ax_array[1, 0].set_xlim([0, 10])
ax_array[0, 1].set_xlim([0, 5])
ax_array[1, 1].set_xlim([0, 5])

# 设置y轴为指数坐标轴
ax_array[0, 0].set_yscale('log')

# 设置双坐标轴(在ax4坐标轴基础上画第2个坐标轴 ax4_twinx)
# ax00 与 ax00_twinx 共用同一个x轴
ax4 = ax_array[1, 1]
ax4_twinx = ax4.twinx()
X4 = np.arange(0, 12.1, 0.1)
Y4 = X + 1
ax4_twinx.plot(X4, Y4, 'r')

# 自动调整布局,并设置间距
figure.tight_layout(
    pad=3.0,      # 画布边缘间距
    w_pad=2.0,    # 水平间距
    h_pad=2.0     # 垂直间距
)
plt.show()

【结果】

相关推荐
IT小盘4 小时前
03-大模型API不只是发送Prompt-流式输出超时重试与异常处理
人工智能·python·prompt
Zzz不能停6 小时前
个人博客系统系统---测试报告【笔耕云】
python·功能测试·自动化·压力测试
互联网中的一颗神经元6 小时前
小白python入门 - 39. 采集流水线小项目
开发语言·python
Wang's Blog7 小时前
Go-Zero 项目开发22:用户群聊功能的实现与完善
开发语言·golang
a1117767 小时前
坦克大战3D Three.js 3D (开源项目)
开发语言·javascript·3d
郭老二7 小时前
【Python】常用模块:xmlrpc
python
名字还没想好☜8 小时前
Python itertools 实战:用 groupby、chain、islice 优雅处理大数据流
linux·windows·python·迭代器·itertools
威联通网络存储8 小时前
TS-h2490FU在面板制造Array段AOI缺陷画廊中的并联
python·制造
Wang's Blog9 小时前
Go-Zero项目开发24: 基于Bitmap实现群聊消息已读未读
开发语言·后端·golang
接针9 小时前
UV 常用命令
python·uv