繁体   English   中英

如何使用 seaborn 配对直方图 plot

[英]How to plot a paired histogram using seaborn

我想使用 seaborn distplot 制作一个像这里显示的那样的配对直方图 这种plot也可以称为此处显示的背靠背直方图,或此处讨论的沿 x 轴倒置/镜像的双直方图。

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

green = np.random.normal(20,10,1000)
blue = np.random.poisson(60,1000)

fig, ax = plt.subplots(figsize=(8,6))

sns.distplot(blue, hist=True, kde=True, hist_kws={'edgecolor':'black'}, kde_kws={'linewidth':2}, bins=10, color='blue')
sns.distplot(green, hist=True, kde=True, hist_kws={'edgecolor':'black'}, kde_kws={'linewidth':2}, bins=10, color='green')
ax.set_xticks(np.arange(-20,121,20))
ax.set_yticks(np.arange(0.0,0.07,0.01))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

plt.show()

这是 output: seaborn 分布图

当我使用此处讨论的方法 (plt.barh) 时,我得到了如下所示的条形 plot,这不是我想要的。 水平条形图

或者也许我对解决方法的理解不够好......类似于这些情节的 python-seaborn-distplot 的简单/简短实现将是完美的。 我在上面编辑了我的第一个 plot 的图形,以显示我希望实现的 plot 的类型(尽管 y 轴没有倒置): 配对直方图

任何线索将不胜感激。

您可以使用两个子图,并用相同的箱反转下一个和 plot 的 y 轴。

df = pd.DataFrame({'a': np.random.normal(0,5,1000), 'b': np.random.normal(20,5,1000)})

fig =plt.figure(figsize=(5,5))
ax = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

bins = np.arange(-20,40)

ax.hist(df['a'], bins=bins)
ax2.hist(df['b'],color='orange', bins=bins)
ax2.invert_yaxis()

在此处输入图像描述

编辑:

@mwaskom 建议的改进

fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True, figsize=(5,5))

bins = np.arange(-20,40)

for ax, column, color, invert in zip(axes.ravel(), df.columns, ['teal', 'orange'],  [False,True]):
    ax.hist(df[column], bins=bins, color=color)
    
    if invert:
        ax.invert_yaxis()
        
plt.subplots_adjust(hspace=0)

在此处输入图像描述

这是使用 seaborn 的分布图的一种可能方法。 Seaborn 不返回创建的图形元素,但可以询问ax 为了确保ax只包含您想要倒置的元素,可以先绘制这些元素。 然后,所有的patches (矩形条)和lines (kde 的曲线)可以被赋予负数。 可以选择使用ax.spines['bottom'].set_position('zero')将 x 轴设置为y == 0

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

green = np.random.normal(20, 10, 1000)
blue = np.random.poisson(60, 1000)

fig, ax = plt.subplots(figsize=(8, 6))

sns.distplot(green, hist=True, kde=True, hist_kws={'edgecolor': 'black'}, kde_kws={'linewidth': 2}, bins=10,
             color='green')
for p in ax.patches:  # turn the histogram upside down
    p.set_height(-p.get_height())
for l in ax.lines:  # turn the kde curve upside down
    l.set_ydata(-l.get_ydata())

sns.distplot(blue, hist=True, kde=True, hist_kws={'edgecolor': 'black'}, kde_kws={'linewidth': 2}, bins=10,
             color='blue')
ax.set_xticks(np.arange(-20, 121, 20))
ax.set_yticks(np.arange(0.0, 0.07, 0.01))
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

pos_ticks = np.array([t for t in ax.get_yticks() if t > 0])
ticks = np.concatenate([-pos_ticks[::-1], [0], pos_ticks])
ax.set_yticks(ticks)
ax.set_yticklabels([f'{abs(t):.2f}' for t in ticks])
ax.spines['bottom'].set_position('zero')

plt.show()

示例图

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM