基于lin上/下组的着色背景

2024-09-28 21:18:08 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个散点图,其中有某种直线(最小二乘回归线、knn回归线等)穿过它,像这样。 enter image description here 我想将图的上部区域着色为红色,而下部区域为蓝色,以说明我的直线作为点的分类器是如何工作的。与我的模拟例子类似的是这个来自Elements of Statistical Learning (Hastie et al)(第2章,第13页)的图。在

enter image description here

如何使用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()

Tags: import区域绘图颜色asnppltrandom
1条回答
网友
1楼 · 发布于 2024-09-28 21:18:08

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

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

然后您可以使用fill_between来填充该行上方(下方)的区域,直到绘图上限(下限)。在

^{pr2}$

enter image description here

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

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

enter image description here

相关问题 更多 >