【问题标题】:Plot Different facecolor in the same axes在相同的轴上绘制不同的 facecolor
【发布时间】:2020-03-16 05:12:56
【问题描述】:

我对 Python 和数据科学有点陌生。

我有一个带有两个输入 x1x2 和一个输出 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()

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

【问题讨论】:

  • 一个格式精美的 Q。喜欢你如何包含所需输出的草图。

标签: python pandas matplotlib data-science


【解决方案1】:

我建议为此使用 matlab 的 fill_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()

【讨论】:

    猜你喜欢
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 2015-08-24
    • 2020-10-12
    • 2019-03-10
    • 2015-04-04
    相关资源
    最近更新 更多