【问题标题】:How to add droplines to a seaborn scatterplot?如何将下降线添加到 seaborn 散点图中?
【发布时间】:2019-08-17 09:01:57
【问题描述】:

在 Jupyter 笔记本中使用以下示例代码:

import pandas as pd
import seaborn as sns
import numpy as np

%matplotlib inline
%config InlineBackend.figure_format = 'svg'

df = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b'])
sns.set()
g = sns.relplot(data=df, x='a', y='b', kind='scatter');
g.set(xlim=(0, 1))
g.set(ylim=(0, 1));

结果图显示了数据点,但我也希望有垂直下降线,偶尔也有水平下降线。为了澄清我所说的下降线的意思,这里是实际输出与所需输出的模型:

更新:更复杂的输入,使手动绘制线条变得更加困难:

import pandas as pd
import seaborn as sns
import numpy as np

%matplotlib inline
%config InlineBackend.figure_format = 'svg'

df = pd.DataFrame(np.random.rand(20, 3), columns=['a', 'b', 'c'])
df['d'] = ['apples', 'bananas', 'cherries', 'dates'] * 5
sns.set()
g = sns.relplot(data=df, x='a', y='b', hue='c', col='d', col_wrap=2, kind='scatter');
g.set(xlim=(0, 1))
g.set(ylim=(0, 1));

【问题讨论】:

  • 如果(x0, y0) 是为其创建线的点,则相应的线将是plt.plot([x0, x0, 0], [0, y0, y0]),对吧?

标签: matplotlib seaborn


【解决方案1】:

有几种方法可以绘制垂直/水平线。其中之一是使用hlinesvlines。为了方便起见,这可以使用循环来完成。

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(121)

fig, ax = plt.subplots()

df = pd.DataFrame(np.random.rand(5, 2), columns=['a', 'b'])
sns.set()
g = sns.relplot(data=df, x='a', y='b', kind='scatter', color='blue', ax=ax);

for x, y in zip(df['a'], df['b']):
    ax.hlines(y, 0, x, color='blue')
    ax.vlines(x, 0, y, color='blue')
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

plt.close(g.fig)

【讨论】:

    猜你喜欢
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2021-08-06
    • 2020-04-29
    • 2020-03-30
    • 2015-01-27
    • 1970-01-01
    相关资源
    最近更新 更多