Python 在同一轴上绘制不同的面颜色

Python 在同一轴上绘制不同的面颜色,python,pandas,matplotlib,data-science,Python,Pandas,Matplotlib,Data Science,我是Python和数据科学的新手 我有一个数据集,有两个输入x1和x2和一个输出y: df=pd.DataFrame({'x1': [1, 2, 2, 1, 0.5, -1, -2, -2, -1, -0.5], 'x2': [1, 1, 2, 2, 0.5, -1, -1, -2, -2, -0.5], 'y': [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]}) x1 x2 y 0 1.0 1.0 0 1 2.0 1.0 0 2 2.0 2.0

我是Python和数据科学的新手

我有一个数据集,有两个输入
x1
x2
和一个输出
y

df=pd.DataFrame({'x1': [1, 2, 2, 1, 0.5, -1, -2, -2, -1, -0.5], 'x2': [1, 1, 2, 2, 0.5, -1, -1, -2, -2, -0.5], 'y': [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]})

    x1   x2  y
0  1.0  1.0  0
1  2.0  1.0  0
2  2.0  2.0  0
3  1.0  2.0  0
4  0.5  0.5  0
5 -1.0 -1.0  1
6 -2.0 -1.0  1
7 -2.0 -2.0  1
8 -1.0 -2.0  1
9 -0.5 -0.5  1
我绘制了这个数据集:

plt.scatter(df.x1[df['y']==1], df.x2[df['y']==1], color='red')
plt.scatter(df.x1[df['y']==0], df.x2[df['y']==0], color='blue')
plt.show()
我想做的是,在同一个图中,为我的类设置一个不同的背景。所以我想要的结果是这样的:

我对Matplotlib不是很熟悉,我所能达到的最好效果是每个类有两个不同的轴,但这不是我真正想做的

import pandas as pd
import matplotlib.pyplot as plt

df=pd.DataFrame({'x1': [1, 2, 2, 1, 0.5, -1, -2, -2, -1, -0.5], 'x2': [1, 1, 2, 2, 0.5, -1, -1, -2, -2, -0.5], 'y': [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]})
fig, (ax0, ax1) = plt.subplots(nrows=1, ncols=2, figsize=(20, 10))
ax0.scatter(df.x1[df1['y']==1], df.x2[df1['y']==1], color='red')
ax0.set_facecolor('xkcd:blue')
ax1.scatter(df.x1[df1['y']==0], df.x2[df1['y']==0], color='blue')
ax1.set_facecolor('xkcd:red')
plt.show()


我想要这个结果,但在相同的轴上,有什么解决方案吗?

我建议使用matlab的
fill\u-between
方法:

注意:您可以创建一个函数,该函数可以动态地构建分隔线的坡度


一个格式很好的问题。喜欢你如何包括你想要的输出草图。
# Get X Values
X = {x for x in df['x1']}
X.update({x for x in df['x2']})
X.update({min(X)-0.25, max(X)+0.25})
X = pd.Series(list(X)).sort_values()


fig, ax = plt.subplots(1,1, figsize=(10, 4))

# Plot the backgrounds first to avoid overwriting the colors
ax.fill_between(X,-1*X,X.min(), color='blue', alpha=0.7)
ax.fill_between(-X,X.max(),(X), color='red', alpha=0.7)

ax.scatter(x = 'x1', y='x2', data = df[df['y']==1], color='red')
ax.scatter(x = 'x1', y='x2', data = df[df['y']==0], color='blue')
plt.show()