如何在海上散点图上添加吊线?

时间:2019-03-26 21:15:01

标签: matplotlib seaborn

在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));

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

Actual vs desired output

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

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));

1 个答案:

答案 0 :(得分: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)

enter image description here