matplotlib
image
本文字数:1.2k 字 | 阅读时长 ≈ 5 min

matplotlib

image
本文字数:1.2k 字 | 阅读时长 ≈ 5 min

1. 安装

pip install matplotlib

2. 基本图形绘制

2.1 基本函数

1. plt.imshow(X, interpolation=None)

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(1)
x = np.random.rand(25, 25, 3)

max = np.max(x)  # 也可以是int类型[0, 255]
x = x*255/max  # expand pixel from [0, 1] to [0, 255], then normalization
x = np.uint8(x) # 可以转化为uint8类型
plt.imshow(x)

如果最后不显示图像的话,需要再加一句 plt.show()

interpolation 参数
这里特别讲一下 interpolation 参数,此参数显示了不同图像之间的插值方式
下面直接给出官方示例:链接

import matplotlib.pyplot as plt
import numpy as np

methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16',
           'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric',
           'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']

np.random.seed(19680801)
grid = np.random.rand(4, 4)
fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6), subplot_kw={'xticks': [], 'yticks': []})

for ax, interp_method in zip(axs.flat, methods):
    ax.imshow(grid, interpolation=interp_method, cmap='viridis')
    ax.set_title(str(interp_method))

plt.tight_layout()
plt.show()

2.plt.subplot()

在当前图片中绘制一个子图

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(1, 10, 20)
y = np.sin(x)

plt.subplot(2,2,1)  # 两行两列,位置为1的子图
plt.plot(x,y)

plt.subplot(222)  # 两行两列,位置为2的子图
plt.barh(x,y)

plt.subplot(224)  # 两行两列,位置为4的子图
plt.bar(x,y)

plt.show()

3. plt.subplots()

返回包含图形和轴对象的元组的函数,将元组加压到 fig 和 ax,看下面的例子

fig, ax = plt.subplots()
x = [1, 2, 3]
y = [1, 2, 3]
ax.plot(x, y)
ax.set_title('Simple plot')
plt.show()

2.2 演示实例

1. 绘制散点图

plt.scatter((x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs))

参数详解:官方手册参数手册

# 绘制一个红色,倒三角的散点图
import numpy as np
import matplotlib.pyplot as plt

x = np.array([1, 2, 3, 4, 5])
y = np.array([5, 4, 3, 2, 1])
plt.scatter(x, y, s=100, c='r', marker='v')
plt.show()

2. 绘制柱形图

from matplotlib import pyplot as plt


y = [10, 11, 12, 11, 9, 8, 13, 10]  # 创建y轴坐标
x = list(range(1,9)) # 创建x轴坐标

# 创建x轴显示的参数(此功能在与在图像中x轴仅显示能被10整除的刻度,避免刻度过多分不清楚)
# x_tick = list(map(lambda num: "" if num % 10 != 0 else num, x))

# plt.figure(figsize=(200, 100), dpi=10)
plt.figure(figsize=(10, 5)) # 创建一个画布

plt.xlabel('This is x label', size=15) # 设置x轴的label
plt.ylabel('This is y label', size=15) # 设置y轴的label

for a,b in zip(x, y):
    plt.text(a, b+0.2, b, ha='center', va='bottom', fontsize=15)  # 给每个柱形图上加上数字
plt.bar(x, y, alpha=0.7, width=0.6, lw=2, label='This is label')  # 绘制条形图

plt.xticks(x, x, size=15)  # 显示x轴刻度
plt.yticks(size=15)        # 显示y轴刻度

plt.title('This is bar caption', fontsize=15)#标题,并设定字号大小
plt.legend(loc=2)#图例展示位置,数字代表第几象限
plt.grid() # 打开网格线

# 获取当前图像句柄
fig = plt.gcf()
plt.show()  #  显示图像
fig.savefig('a.png')  # 存储图像
plt.show()

柱状图如下

9月 09, 2024
9月 06, 2024