基于组above/below一行的底纹背景

Shading background based on groups above/below a line

假设我有一个散点图,其中有某种线(最小二乘回归线、knn 回归线等)穿过它,就像这样。 我想将图的上部区域涂成红色,将图的下部区域涂成蓝色,以指示我的线作为点的分类器的表现如何。 Elements of Statistical Learning (Hastie et al)(第 2 章,第 13 页)中的这个图与我具有这种效果的模拟示例类似。

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


我知道如何使用 axhspanaxvspan 将绘图的矩形区域设置为不同的颜色(参见 this answer),但一直在努力设置不同的绘图颜色在 上方和下方的区域。

复制我当前模拟情节的代码

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()

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

x = np.sort(full_x)
plt.plot(x, m*x + c, color='black')

然后您可以使用 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)

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

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("\\")