首页 > 编程技术 > python

python Matplotlib模块的使用

发布时间:2020-9-16 16:15

一、Matplotlib简介与安装

  Matplotlib也就是Matrix Plot Library,顾名思义,是Python的绘图库。它可与NumPy一起使用,提供了一种有效的MATLAB开源替代方案。它也可以和图形工具包一起使用,如PyQt和wxPython。
  安装方式:执行命令 pip install matplotlib
  一般常用的是它的子包PyPlot,提供类似MATLAB的绘图框架。

二、使用方法

1.绘制一条直线 y = 3 * x + 4,其中 x 在(-2, 2),取100个点平均分布

# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
import numpy as np

# 创建数据
x = np.linspace(-2, 2, 100)
y = 3 * x + 4

# 创建图像
plt.plot(x, y)

# 显示图像
plt.show()

2.在一张图里绘制多个子图

# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt

from matplotlib.ticker import NullFormatter

"""
多个子图
"""

# 为了能够复现
np.random.seed(1)

y = np.random.normal(loc=0.5, scale=0.4, size=1000)
y = y[(y > 0) & (y < 1)]
y.sort()
x = np.arange(len(y))

plt.figure(1)

# linear
# 使用.subplot()方法创建子图,221表示2行2列第1个位置
plt.subplot(221)
plt.plot(x, y)
plt.yscale('linear')
plt.title('linear')
plt.grid(True)

# log
plt.subplot(222)
plt.plot(x, y)
plt.yscale('log')
plt.title('log')
plt.grid(True)

# symmetric log
plt.subplot(223)
plt.plot(x, y - y.mean())
plt.yscale('symlog', linthreshy=0.01)
plt.title('symlog')
plt.grid(True)

# logit
plt.subplot(224)
plt.plot(x, y)
plt.yscale('logit')
plt.title('logit')
plt.grid(True)
plt.gca().yaxis.set_minor_formatter(NullFormatter())
plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10, right=0.95, hspace=0.25,
          wspace=0.35)

plt.show()

3.绘制一个碗状的3D图形,着色使用彩虹色

# -*- coding: utf-8 -*-

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

"""
碗状图形
"""

fig = plt.figure(figsize=(8, 5))
ax1 = Axes3D(fig)

alpha = 0.8
r = np.linspace(-alpha, alpha, 100)
X, Y = np.meshgrid(r, r)
l = 1. / (1 + np.exp(-(X ** 2 + Y ** 2)))

ax1.plot_wireframe(X, Y, l)
ax1.plot_surface(X, Y, l, cmap=plt.get_cmap("rainbow")) # 彩虹配色
ax1.set_title("Bowl shape")

plt.show()

4.更多用法

参见官网文档

以上就是python Matplotlib模块的使用的详细内容,更多关于python Matplotlib模块的资料请关注猪先飞其它相关文章!

标签:[!--infotagslink--]

您可能感兴趣的文章: