Matplotlib

基本演示

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
y = x * x
plt.plot(x, y)
plt.show()

figure

x = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2

plt.figure()
plt.plot(x, y1)

plt.figure(num=3, figsize=(6, 6))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')

plt.show()

坐标轴

x = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2

plt.figure(num=3, figsize=(6, 6))
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')

# 坐标范围
plt.xlim((-1, 2))
plt.ylim((-2, 3))

# 轴标签
plt.xlabel('I am X')
plt.ylabel('I am Y')

# 坐标轴上的数字/字符
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.5, -1, 1.2, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])

# 移动x,y轴
ax = plt.gca()  # get current axis
ax.spines['right'].set_color('none')    # 上下左右四个边框叫spines
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')   # 用下面的坐标轴作为x轴
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))   # 移动x轴
ax.spines['left'].set_position(('data', 0))

plt.show()

图例

x = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2

plt.figure(num=3, figsize=(6, 6))

# 坐标范围
plt.xlim((-1, 2))
plt.ylim((-2, 3))

# 轴标签
plt.xlabel('I am X')
plt.ylabel('I am Y')

# 坐标轴上的数字/字符
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.5, -1, 1.2, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])

# plt.plot(x, y2, label='up')
# plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='down')
# plt.legend()  # 默认图例

l1, = plt.plot(x, y2, label='up')
l2, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='down')
plt.legend(handles=[l1, l2,], labels=['aaa', 'bbb',], loc='best')
# plt.legend(handles=[l1,], labels=['aaa',], loc='best')  # 只打印一个

plt.show()

注解

x = np.linspace(-3, 3, 50)
y = 2 * x + 1

plt.figure(num=1, figsize=(6, 6))
plt.plot(x, y)

ax = plt.gca()  # get current axis
ax.spines['right'].set_color('none')    # 上下左右四个边框叫spines
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')   # 用下面的坐标轴作为x轴
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))   # 移动x轴
ax.spines['left'].set_position(('data', 0))

# scatter表示点,plot表示线
x0 = 1
y0 = 2 * x0 + 1
plt.scatter(x0, y0, s=50, color='b')
plt.plot([x0, x0], [y0, 0], 'k--', lw=2.5)

# 注解
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data',   # 注解坐标和参照
             xytext=(+30, -30), textcoords='offset points', # 文字的坐标和参照
             fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))  # 字号,箭头的属性

# 文本
plt.text(-3.7, 3, r'$This\ is\ some\ text.\ \mu\ \sigma_i\ \alpha_t$',
         fontdict={'size':16, 'color':'r'})

plt.show()

能见度

坐标轴数据被挡住了

x = np.linspace(-3, 3, 50)
y = 0.1 * x

plt.figure(num=1, figsize=(6, 6))
plt.plot(x, y, lw=10)
plt.ylim(-2, 2)

ax = plt.gca()  # get current axis
ax.spines['right'].set_color('none')    # 上下左右四个边框叫spines
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')   # 用下面的坐标轴作为x轴
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0))   # 移动x轴
ax.spines['left'].set_position(('data', 0))

for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    # 设置坐标轴数据的底色,不显示边框,透明度
    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7))

散点图

n = 1024
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
t = np.arctan2(y, x)    # for color value

# 传入数值,大小,颜色,透明度
plt.scatter(x, y, s=75, c=t, alpha=0.5)

plt.xlim((-1.5, 1.5))
plt.ylim((-1.5, 1.5))
plt.xticks(())
plt.yticks(())
plt.show()

柱状图

n = 12
X = np.arange(n)
y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)

plt.bar(X, y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, -y2, facecolor='#ff9999', edgecolor='white')

for x, y in zip(X, y1):
    plt.text(x, y + 0.05, '%.2f' % y, ha='center', va='bottom')   # 横纵对齐方式
for x, y in zip(X, y2):
    plt.text(x, -y - 0.05, '%.2f' % -y, ha='center', va='top')   # 横纵对齐方式

plt.ylim((-1.25, 1.25))

plt.show()

等高线

def f(x, y):
    return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)    # 基于向量返回二维网格坐标

# 设置颜色,8为分层数,hot为暖色
plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)

# 画线
C = plt.contour(X, Y, f(X, Y), 8, colors='black')

plt.clabel(C, inline=True, fontsize=10)

plt.xticks(())
plt.yticks(())
plt.show()

图片

a = np.array([0.31, 0.36, 0.42, 0.36, 0.43, 0.52, 0.42, 0.52, 0.65]).reshape(3, 3)

plt.imshow(a, interpolation='nearest', cmap='bone', origin='upper')
plt.colorbar(shrink=0.9)

plt.xticks(())
plt.yticks(())
plt.show()

多合一

plt.figure()

plt.subplot(2, 2, 1)    # 两行两列的第1张图
plt.plot([0,1], [0,1])
plt.subplot(2, 2, 2)
plt.plot([0,1], [0,2])
plt.subplot(2, 2, 3)
plt.plot([0,1], [0,3])
plt.subplot(2, 2, 4)
plt.plot([0,1], [0,4])

plt.show()

plt.figure()

plt.subplot(2, 1, 1)
plt.plot([0,1], [0,1])
plt.subplot(2, 3, 4)
plt.plot([0,1], [0,2])
plt.subplot(2, 3, 5)
plt.plot([0,1], [0,3])
plt.subplot(2, 3, 6)
plt.plot([0,1], [0,4])

plt.show()

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

# 总共是3*3的网格,从0,0开始,所占列数行数
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
ax1.plot([1,2],[1,2])
ax1.set_title('ax1_title')

ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))

import matplotlib.gridspec as gridspec
plt.figure(figsize=(6, 6))
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
ax2 = plt.subplot(gs[1, :2])
ax3 = plt.subplot(gs[1:, 2])
ax4 = plt.subplot(gs[-1, 0])
ax5 = plt.subplot(gs[-1, -2])

plt.show()

主次坐标轴

x = np.arange(0, 10, 0.1)
y1 = 0.05 * x ** 2
y2 = -1 * y1

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b--')

plt.show()


Matplotlib
https://shuusui.site/blog/2022/09/13/matplotlib/
作者
Shuusui
发布于
2022年9月13日
更新于
2022年9月13日
许可协议