假设我有一个散点图,其中有某种直线(最小二乘回归线、knn回归线等)穿过它,像这样。 我想将图的上部区域着色为红色,而下部区域为蓝色,以说明我的直线作为点的分类器是如何工作的。与我的模拟例子类似的是这个来自Elements of Statistical Learning (Hastie et al)(第2章,第13页)的图。在
如何使用Matplotlib实现这种效果?在
我知道如何用axhspan
和axvspan
将绘图的矩形区域设置为不同的颜色(请参见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
值进行排序,使该行看起来平滑。在然后您可以使用
^{pr2}$fill_between
来填充该行上方(下方)的区域,直到绘图上限(下限)。在或者使用一些阴影作为背景:
相关问题 更多 >
编程相关推荐