基于线上/线下组的底纹背景

Eri*_*sen 4 python plot regression matplotlib

假设我有一个散点图,上面有某种线(最小二乘回归线、knn 回归线等),就像这样。 在此处输入图片说明 我想将绘图的上部区域涂成红色,将绘图的下部区域涂成蓝色,以表明我的线作为点的分类器的表现如何。与我的具有此效果的模拟示例类似,来自Elements of Statistical Learning ( Hastie 等人) (第 2 章,第 13 页) 中的此图。

在此处输入图片说明

如何使用 Matplotlib 实现这种效果?


我知道如何使用axhspan和将绘图的矩形区域设置为不同的颜色axvspan(请参阅此答案),但一直在努力根据线条上方和下方的区域设置不同的绘图颜色。

复制我当前模拟图的代码

import numpy as np
import matplotlib.pyplot as plt

plt.style.use('seaborn-notebook')

np.random.seed(17)
grp1_x = np.random.normal(1, 1, 100)
grp1_y = np.random.normal(3, 1, 100)

grp2_x = np.random.normal(1.2, 1, 100)
grp2_y = np.random.normal(1.2, 1, 100)

########################################
## least squares plot

plt.scatter(grp1_x, grp1_y,
            lw         = 1,
            facecolors = 'none',
            edgecolors = 'firebrick')
plt.scatter(grp2_x, grp2_y,
            lw         = 1,
            facecolors = 'none',
            edgecolors = 'steelblue')
plt.tick_params(
    axis        = 'both',
    which       = 'both',
    bottom      = 'off',
    top         = 'off',
    labelbottom = 'off',
    right       = 'off',
    left        = 'off',
    labelleft   = 'off')

full_x = np.concatenate([grp1_x, grp2_x])
full_y = np.concatenate([grp1_y, grp2_y])
m, c = np.linalg.lstsq(np.vstack([full_x,
                                  np.ones(full_x.size)]).T,
                       full_y)[0]
plt.plot(full_x, m*full_x + c, color='black')
plt.show()
Run Code Online (Sandbox Code Playgroud)

Imp*_*est 7

首先,我建议对x值进行排序,使线条看起来平滑。

x = np.sort(full_x)
plt.plot(x, m*x + c, color='black')
Run Code Online (Sandbox Code Playgroud)

然后您可以使用fill_between填充线上方(下方)到(从)上(下)图限制的区域。

xlim=np.array(plt.gca().get_xlim())
ylim=np.array(plt.gca().get_ylim())
plt.fill_between(xlim, y1=m*xlim + c, y2=[ylim[0],ylim[0]], 
                 color="#e0eaf3", zorder=0 )
plt.fill_between(xlim, y1=m*xlim + c, y2=[ylim[1],ylim[1]], 
                 color="#fae4e4", zorder=0 )
plt.margins(0)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

或者使用一些阴影作为背景:

fb1 = plt.fill_between(xlim, y1=m*xlim + c, y2=[ylim[0],ylim[0]], 
                 facecolor="w", edgecolor="#e0eaf3", zorder=0 )
fb1.set_hatch("//")
fb2 = plt.fill_between(xlim, y1=m*xlim + c, y2=[ylim[1],ylim[1]], 
                  facecolor="w", edgecolor="#fae4e4", zorder=0 )
fb2.set_hatch("\\\\")
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明