分享

如何驾驭Matplotlib?<Part1>

 隔壁老孙2nlntu 2023-02-12 发布于湖南

共12个章节,本文为第1~4章节。

图片❤️本文速


目录

1 准备工作
1.1 Matplotlib安装
1.2 Matplotlib版本查看
1.3 Matplotlib默认参数设置

2、散点图
2.1 默认散点图
2.2 散点图点大小、颜色设置
2.3 散点图标记、点动态变化
2.4 散点图colormap、透明度设置

3、折线图
3.1 默认折线图
3.2 折线图线型、分面设置
3.3 折线图线宽设置 
3.4 折线图标记设置
3.5 折线图多标记、标记间距设置
3.6 折线图误差线设置
3.7 折线图仅保留误差线
3.8 折线图填充设置
3.9 折线图添加垂直线
3.10 折线图添加垂直平面

4、直方图
4.1 默认直方图
4.2 直方图bins数设置
4.3 直方图配色、轴范围设置
4.4 水平直方图 
4.5 直方图bins添加边界线 
4.6 多组直方图  
4.7 直方图修改箱子透明度
4.8 更多组直方图  
4.9 2D直方图 
4.10 2D直方图修改bins数
4.11 2D直方图定义colormap
4.12 2D直方图显示范围内变量 
4.13 边界直方图
图片

1 准备工作

1.1 Matplotlib安装

#方法1 使用pip安装
pip install matplotlib

#方法2 使用conda安装
conda install matplotlib

1.2  Matplotlib版本查看

Matplotlib版本查看,

# matplotlib版本查看
pip show matplotlib

图片本文使用的是Matplotlib 3.6.2版本。

1.3 Matplotlib默认参数设置

# 默认参数设置
import matplotlib.pyplot as plt

plt.rcParams['font.size'] = 15  #设置字号
plt.rcParams['font.family'] = 'serif'  #设置字体

tdir = 'out'
major = 5.0
minor = 3.0
plt.rcParams['xtick.direction'] = tdir  #x轴刻度线朝外,PS刻度线为数字与坐标轴之间的连线
plt.rcParams['ytick.direction'] = tdir  #y轴刻度线朝外
plt.rcParams['xtick.major.size'] = major  #x轴主刻度线长度
plt.rcParams['xtick.minor.size'] = minor  #x轴副刻度线长度
plt.rcParams['ytick.major.size'] = major  #y轴主刻度线长度
plt.rcParams['ytick.minor.size'] = minor  #y轴副刻度线长度

默认参数设定后,后续绘图涉及以上参数的地方都采用此处值。图片

2、散点图

该部分通过散点图介绍Matplotlib使用。

2.1 默认散点图

绘图数据准备,

#准备绘图数据
import numpy as np  # 导入依赖numpy
import matplotlib.pyplot as plt  #导入matplotlib

N = 50
x = np.linspace(0.10., N)  #x变量数据:使用numpy生成长度为50的数组,范围在1~10之间
y = np.sin(x)**2 + np.cos(x)  #y变量数据:基与x生成y

x,y变量预览,图片

plt.figure()  #figure生成一幅Figure
plt.scatter(x, y)  #scatter函数绘制散点图
图片

2.2 散点图点大小、颜色设置

下面对点大小固定变化、颜色、图例进行调整以美化图形,

plt.figure()
plt.scatter(x, y, s=15, label=r'$ y  = sin^2(x) + cos(x), color='r')
#s设置点的大小
#label设置图例名称
#color设置点颜色

plt.axis('
equal')  #x轴和y轴单位长度相同。还有一个plt.axis('square')将x轴和y轴长度设置相等,即图是正方形。

plt.legend()  # 开启图例
plt.xlabel(r'
$x$ (rad)')  # 设置x轴标题
plt.ylabel(r'
$y)  # 设置y轴标题
plt.show()  #图形渲染/展示
图片

2.3 散点图标记、点动态变化

设置图形分辨率、点marker、点大小动态变化,更多marker修改👉一文掌握marker使用

plt.figure(dpi=100)  #设置图形分辨率,控制图形清晰度
plt.scatter(
    x,
    y,
    s=x,  #点大小随变量x大小变化
    marker='^',  #设置点的marker为三角形
    label=r'$ y  = sin^2(x) + cos(x),
    color='
r')

plt.axis('
equal')
plt.legend()
plt.xlabel(r'
$x$ (rad)')
plt.ylabel(r'
$y)
plt.show()
图片

2.4 散点图colormap、透明度设置

设置点颜色动态变化、设置点colormap、透明度,了解详细颜色设置👉Python可视化调色盘colormap

from matplotlib import cm

plt.figure(dpi=150)
plt.scatter(
    x,
    y,
    s=x,
    c=x,  #点颜色随变量x大小变化
    marker='^',
    label=r'$ y  = sin^2(x) + cos(x),
    alpha=.8, #设置点透明度
    cmap=cm.get_cmap('
Blues'))  #设置colormap

plt.axis('
equal')
plt.legend()
plt.xlabel(r'
$x$ (rad)')
plt.ylabel(r'
$y)
plt.colorbar()  #添加colorbar
plt.show()
图片
图片

3、折线图

该部分通过折线图介绍Matplotlib使用。

3.1 默认折线图

#准备绘图数据
N = 50
x = np.linspace(0.10., N)
y = np.sin(x)**2 + np.cos(x)

#散点图绘制
plt.plot(x, y)
plt.show()
图片

3.2 折线图线型、分面设置

修改折线图线型、分面展示,

N = 50

x = np.linspace(0.10., N)
y = np.sin(x)**2 + np.cos(x)

rows = 2
columns = 2
grid = plt.GridSpec(rows, columns, wspace=.25, hspace=.25)
#分面为4张图展示不同线型,分面此处使用GridSpec()方法
#还可以使用subplot()、add_subplot()方法

linestyles = ['-''--''-.'':']

plt.figure(dpi=120)
for i in range(len(linestyles)):
    plt.subplot(grid[i])
    plt.plot(
        x,
        y,
        linestyle=linestyles[i],  #linestyle设置线型
        label=r'$ y  = sin^2(x) + cos(x))
    plt.axis('
equal')
    plt.xlabel('
$x$ (rad)')
    plt.legend()

    #添加文字注释
    plt.annotate('linestyle '
' + str(linestyles[i]) + ''',
                 xy=(0.5, -2.5),
                 va='
center',
                 ha='
left')
图片

3.3 折线图线宽设置

修改折线图线宽,

N = 50

rows = 2
columns = 2

x = np.linspace(0.10., N)
y = np.sin(x)**2 + np.cos(x)

grid = plt.GridSpec(rows, columns, wspace=.25, hspace=.25)

linewidth = [2345]

plt.figure(dpi=150)
for i in range(len(linestyles)):
    plt.subplot(grid[i])
    plt.plot(
        x,
        y,
        linestyle='-.',
        lw=linewidth[i],  #lw设置线宽
        label=r'$ y  = sin^2(x) + cos(x))
    plt.axis('
equal')
    plt.xlabel('
$x$ (rad)')
    plt.legend()
    plt.annotate('linewidth ' + str(linewidth[i]),
                 xy=(0.5, -2.5),
                 va='
center',
                 ha='
left')
图片

3.4 折线图标记设置

折线图添加marker,

N = 50

x = np.linspace(0.10., N)
y = np.sin(x)**2 + np.cos(x)

plt.figure(dpi=150)
plt.plot(
    x,
    y,
    'o',
    ls='-.',
    lw=2,
    ms=7,  #marker大小
    markevery=12,  #每隔12个点添加marker
    label=r'$ y  = sin^2(x) + cos(x))
plt.axis('
equal')
plt.xlabel('
$x$ (rad)')
plt.legend()
plt.annotate('markevery: 5', xy=(0.5, -2.5), va='
center', ha='left')
图片

3.5 折线图多标记、标记间距设置

不同折线图添加不同marker、按照不同的间距,

N = 50

x = np.linspace(0.10., N)
y = np.sin(x)**2 + np.cos(x)

rows = 2
columns = 2

grid = plt.GridSpec(rows, columns, wspace=.25, hspace=.25)

mark = [581315]
color = ['#00429d''#627c94''#f4777f''#93003a']

plt.figure(dpi=150)
for i in range(len(linestyles)):
    plt.subplot(grid[i])
    plt.plot(
        x,
        y,
        'o',
        ls='-.',
        lw=2,
        ms=8,
        markevery=mark[i],  #不同间隔
        color=color[i],  #不同颜色
        label=r'$ y  = sin^2(x) + cos(x))
    plt.axis('
equal')
    plt.annotate('markevery: ' + str(mark[i]),
                 xy=(0.5, -2.5),
                 va='
center',
                 ha='
left')
    plt.xlabel('
$x$ (rad)')
    plt.legend()
图片

3.6 折线图误差线设置

折线图添加误差线,

N = 25
x = np.linspace(0.10., N)
y = np.sin(x)**2 + np.cos(x)

np.random.seed(100)
noise_x = np.random.random(N) * .2 + .1
noise_y = np.random.random(N) * .7 + .4

plt.figure(dpi=120)

#使用errorbar方法添加误差线
plt.errorbar(
    x,
    y,
    yerr=noise_y,  #y轴方向添加误差线
    xerr=noise_x,  #x轴方向添加误差线
    label=r'$ y  = sin^2(x) + cos(x))
plt.axis('
equal')
plt.legend()
plt.xlabel('
$x$ (rad)')
图片

3.7 折线图仅保留误差线

去掉折线,只保留误差线,

N = 25

x = np.linspace(0.10., N)
y = np.sin(x)**2 + np.cos(x)

np.random.seed(100)
noise_x = np.random.random(N) * .2 + .1
noise_y = np.random.random(N) * .7 + .4

plt.figure(dpi=150)
plt.errorbar(
    x,
    y,
    xerr=noise_x,
    yerr=noise_y,
    label=r'$ y  = sin^2(x) + cos(x),
    color='
r',  #marker颜色
    fmt='
o',  #marker形状
    ecolor='
blue',  #误差线颜色
)
plt.axis('
equal')
plt.legend()
plt.xlabel('
$x$ (rad)')
图片

3.8 折线图填充设置

折线图区域填充,

N = 25
x = np.linspace(0.10., N)
y = np.sin(x)**2 + np.cos(x)

np.random.seed(100)
noise = np.random.random(N) * .7 + .4

plt.figure(dpi=120)
plt.plot(x, y, ls='-', label=r'$ y  = sin^2(x) + cos(x))

#使用fill_between方法
plt.fill_between(
    x,
    y + noise,  #y轴上方区域
    y - noise,  #y轴下方区域
    alpha=.3)
plt.axis('
equal')
plt.legend()
plt.xlabel('
$x$ (rad)')
图片

3.9 折线图添加垂直线

添加x轴、y轴方向垂直线,

N = 25

x = np.linspace(0.10., N)
y = np.sin(x)**2 + np.cos(x)

np.random.seed(100)
noise = np.random.random(N) * .7 + .4

plt.figure(dpi=120)
plt.plot(x, y, ls='-', label=r'$ y  = sin^2(x) + cos(x), color='darkgreen')
plt.fill_between(x, y + noise, y - noise, color='
darkgreen', alpha=.3)
plt.axis('
equal')

#hlines绘制水品线
plt.hlines(
    0,  #y轴位置
    xmin=0,  #x轴起始位置
    xmax=10,  #x轴终止位置
    ls='
--',  #线型
    color='
red',  #线颜色
    label='
hlines')  #图例

#hlines绘制垂直线
plt.vlines(2, ymin=-3, ymax=3, ls='
--', color='blue', label='vlines')

plt.legend()
plt.xlabel('
$x$ (rad)')
图片

3.10 折线图添加垂直平面

添加y轴方向垂直平面,

N = 25

x = np.linspace(0.10., N)
y = np.sin(x)**2 + np.cos(x)

np.random.seed(100)
noise = np.random.random(N) * .7 + .4

plt.figure(dpi=120)
plt.plot(x, y, ls='-', label=r'$ y  = sin^2(x) + cos(x), color='darkgreen')
plt.fill_between(x, y + noise, y - noise, color='
darkgreen', alpha=0.3)

plt.axis('
equal')

plt.fill_between((2, 4), -3.2, 3.2, facecolor='
blue', alpha=0.3)

plt.xlim(0, 10)
plt.ylim(-3, 3)

plt.legend()
plt.xlabel('
$x$ (rad)')
图片
图片

4、直方图

该部分通过直方图介绍Matplotlib使用。

4.1 默认直方图

N = 1000
np.random.seed(10021)
x = np.random.randn(N) * 2 + 15
plt.hist(x)

图片默认分箱bins为10个。

4.2 直方图bins数设置

修改分箱bins数目。

N = 1000
np.random.seed(10021)
x = np.random.randn(N) * 2 + 15
plt.figure(dpi=120)
plt.hist(
    x,
    bins=40,  #设置bins数目为40个
    label=r'$\mu = 15, \sigma = 2  #添加图例
)
plt.legend()
图片

4.3 直方图配色、轴范围设置

修改配色、横轴显示范围。

N = 1000

np.random.seed(10021)
x = np.random.randn(N) * 2 + 15

plt.figure(dpi=120)

plt.hist(x,
         bins=40,
         range=(1218),#设置横轴显示范围
         color='pink'#修改配色
         label=r'$\mu = 15, \sigma = 2)

plt.legend()
图片

4.4 水平直方图

绘制水平方向直方图。

N = 1000

np.random.seed(10021)
x = np.random.randn(N) * 2 + 15

plt.figure(dpi=120)
plt.hist(
    x,
    bins=25,
    range=(1218),
    color='royalblue',
    orientation='horizontal',  #水平方向直方图
    label=r'$\mu = 15, \sigma = 2)
plt.legend()
图片

4.5 直方图bins添加边界线

为直方图bins添加边界线。

N = 1000

np.random.seed(10021)
x = np.random.randn(N) * 2 + 15

plt.figure(dpi=120)
plt.hist(
    x,
    bins=25,
    range=(1218),
    color='royalblue',
    orientation='horizontal',
    edgecolor='k',  #bins边界上色
    label=r'$\mu = 15, \sigma = 2)
plt.legend()
图片

4.6 多组直方图

N = 1000

mu1 = 5
mu2 = 10
mu3 = 15

sigma1 = 5
sigma2 = 3
sigma3 = 2

x1 = np.random.randn(N) * sigma1 + mu1
x2 = np.random.randn(N) * sigma2 + mu2
x3 = np.random.randn(N) * sigma3 + mu3

plt.figure(dpi=120)

plt.hist(
    x1,  #变量1
    bins=30,
    color='royalblue',
    label=r'$\mu = $ ' + str(mu1) + ', $\sigma = $ ' + str(sigma1))
plt.hist(
    x2,  #变量2
    bins=30,
    color='tomato',
    label=r'$\mu = $ ' + str(mu2) + ', $\sigma = $ ' + str(sigma2))
plt.hist(
    x3,  #变量3
    bins=30,
    color='gray',
    label=r'$\mu = $ ' + str(mu3) + ', $\sigma = $ ' + str(sigma3))
plt.legend()
图片

4.7 直方图修改箱子透明度

N = 1000

mu1 = 5
mu2 = 10
mu3 = 15

sigma1 = 5
sigma2 = 3
sigma3 = 2

x1 = np.random.randn(N) * sigma1 + mu1
x2 = np.random.randn(N) * sigma2 + mu2
x3 = np.random.randn(N) * sigma3 + mu3

plt.figure(dpi=120)

plt.hist(x1,
         bins=30,
         color='royalblue',
         label=r'$\mu = $ ' + str(mu1) + ', $\sigma = $ ' + str(sigma1),
         alpha=.7 #透明度通过alpha设置
        )
plt.hist(x2,
         bins=30,
         color='tomato',
         label=r'$\mu = $ ' + str(mu2) + ', $\sigma = $ ' + str(sigma2),
         alpha=.7)
plt.hist(x3,
         bins=30,
         color='gray',
         label=r'$\mu = $ ' + str(mu3) + ', $\sigma = $ ' + str(sigma3),
         alpha=.7)
plt.legend()

图片  以上代码可以通过循环简化,

N = 1000
mu1 = 5
mu2 = 10
mu3 = 15
sigma1 = 5
sigma2 = 3
sigma3 = 2
x1 = np.random.randn(N) * sigma1 + mu1
x2 = np.random.randn(N) * sigma2 + mu2
x3 = np.random.randn(N) * sigma3 + mu3
mu = np.array([mu1, mu2, mu3])
sigma = np.array([sigma1, sigma2, sigma3])
x = np.array([x1, x2, x3])
colors = ['royalblue''tomato''gray']
plt.figure(dpi=120)

#循环方式绘图
for i in range(len(x)):
    plt.hist(x[i], bins = 30, color = colors[i], 
             label = r'$\mu = $ ' + str(mu[i]) + 
             ', $\sigma = $ ' + str(sigma[i]), alpha = .7)
plt.legend()

4.8 更多组直方图

通过循环,我们可以一图绘制更多直方图。

N_func = 10
N_data = 1000

np.random.seed(1000)

mu = np.random.randint(low=-5, high=5, size=N_func)
sigma = np.random.randint(low=1, high=5, size=N_func)

x = []
for i in range(len(mu)):
    xi = np.random.randn(N_data) * sigma[i] + mu[i]
    x.append(xi)

colors = [
    '#00429d''#7f40a2''#a653a1''#c76a9f''#e4849c''#d0e848',
    '#b6cf54''#a9b356''#b2914b''#ff0001'
]

plt.figure(dpi=120)
for i in range(len(mu)):
    plt.hist(x[i],
             bins=30,
             color=colors[i],
             label=r'$\mu = $ ' + str(mu[i]) + ', $\sigma = $ ' +
             str(sigma[i]),
             alpha=.7)

plt.legend(bbox_to_anchor=(1.331.03))
图片

4.9 2D直方图

N = 1_000
np.random.seed(100)
x = np.random.randn(N)
y = np.random.randn(N)
plt.hist2d(x, y)  #2D直方图需要传入两个变量
图片

4.10 2D直方图修改bins数

N = 1_000
np.random.seed(100)
x = np.random.randn(N)
y = np.random.randn(N)
plt.hist2d(x, y, bins=(2525))  #2D直方图修改bins也需要传入两个变量
图片

4.11 2D直方图定义colormap

from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap

top = cm.get_cmap('Oranges_r'128)
bottom = cm.get_cmap('Blues'128)

newcolors = np.vstack((top(np.linspace(01,
                                       128)), bottom(np.linspace(01128))))
orange_blue = ListedColormap(newcolors, name='OrangeBlue')  #自定义colormap

N = 10_000

np.random.seed(100)
x = np.random.randn(N)
y = np.random.randn(N)

plt.figure(dpi=120)
plt.hist2d(
    x,
    y,
    bins=(7575),
    cmap=orange_blue  #传入colormap
)
cb = plt.colorbar()
cb.set_label('counts each bin', labelpad=10)
图片

4.12 2D直方图显示范围内变量

N = 10_000
np.random.seed(100)
x = np.random.randn(N)
y = np.random.randn(N)
plt.figure(dpi=120)
plt.hist2d(x, y, bins=(7575), cmap='jet'
           cmin=5, cmax=25 #定义
          )
cb = plt.colorbar()
cb.set_label('counts each bin', labelpad=10)
图片

4.13 边界直方图

N = 10_000

np.random.seed(100)
x = np.random.randn(N)
y = np.random.randn(N)

rows = 5
columns = 5

grid = plt.GridSpec(rows, columns, wspace=.4, hspace=.4)

plt.figure(dpi=120)

plt.subplot(grid[00:-1])
plt.hist(x, bins=40, color='royalblue', alpha=.6)
plt.annotate('Normal 1', xy=(2500), va='center', ha='left')

plt.subplot(grid[1:rows + 10:-1])
plt.hist2d(x, y, cmap='Blues', bins=(3040))
plt.axis('equal')

plt.subplot(grid[1:rows + 1-1])
plt.hist(y, bins=40, orientation='horizontal', color='royalblue', alpha=.6)
plt.annotate('Normal 2', xy=(5002), va='bottom', ha='center', rotation=-90)

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多