更改海运直方图(或PLT)中用于数据选择的条的颜色 [英] change color of bar for data selection in seaborn histogram (or plt)

查看:34
本文介绍了更改海运直方图(或PLT)中用于数据选择的条的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的数据帧:

X2 = np.random.normal(10, 3, 200)
X3 = np.random.normal(34, 2, 200)

a = pd.DataFrame({"X3": X3, "X2":X2})

我正在执行以下绘图例程:

f, axes = plt.subplots(2, 2,  gridspec_kw={"height_ratios":(.10, .30)}, figsize = (13, 4))
for i, c in enumerate(a.columns):
    sns.boxplot(a[c], ax=axes[0,i])
    sns.distplot(a[c], ax = axes[1,i])
    axes[1, i].set(yticklabels=[])
    axes[1, i].set(xlabel='')
    axes[1, i].set(ylabel='')

plt.tight_layout()
plt.show()

以下对象:

现在我希望能够在数据帧a上执行数据选择。让我们假设:

b = a[(a['X2'] <4)]

并在张贴的直方图中突出显示b中的选项。 例如,如果b的第一行对于X3为[32:0],对于X2为[0:5],则所需的输出将为:

是否可以使用上面的for loop和SNS实现这一点?非常感谢!

编辑:我对matplotlib解决方案也很满意,如果更容易的话。

EDIT2:

如果有帮助,它将类似于执行以下操作:

b = a[(a['X3'] >38)]

f, axes = plt.subplots(2, 2,  gridspec_kw={"height_ratios":(.10, .30)}, figsize = (13, 4))

for i, c in enumerate(a.columns):
   sns.boxplot(a[c], ax=axes[0,i])
   sns.distplot(a[c], ax = axes[1,i])
   sns.distplot(b[c], ax = axes[1,i])

   axes[1, i].set(yticklabels=[])
   axes[1, i].set(xlabel='')
   axes[1, i].set(ylabel='')

plt.tight_layout()
plt.show()

这将产生以下结果:

但是,我希望能够用不同的颜色为第一个图中的条形图上色! 我还考虑过将ylim设置为仅为蓝色地块的大小,以便橙色不会扭曲蓝色分布的形状,但这仍然不可行,因为实际上我有大约10个直方图要显示,并且设置ylim将与Shary=True几乎相同,这是我试图避免的,这样我就能够显示分布的真实形状。

推荐答案

我想我从上一个答案和this视频中得到了解决方案:

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

np.random.seed(2021)
X2 = np.random.normal(10, 3, 200)
X3 = np.random.normal(34, 2, 200)

a = pd.DataFrame({"X3": X3, "X2":X2})
b = a[(a['X3'] < 30)]


hist_idx=[]

for i, c in enumerate(a.columns):
    bin_ = np.histogram(a[c], bins=20)[1]
    hist = np.where(np.logical_and(bin_<=max(b[c]), bin_>min(b[c])))
    hist_idx.append(hist)
    

f, axes = plt.subplots(2, 2,  gridspec_kw={"height_ratios":(.10, .30)}, figsize = (13, 4))

for i, c in enumerate(a.columns):
    sns.boxplot(a[c], ax=axes[0,i])
    axes[1, i].hist(a[c], bins = 20)
    axes[1, i].set(yticklabels=[])
    axes[1, i].set(xlabel='')
    axes[1, i].set(ylabel='')
    
for it, index in enumerate(hist_idx):
    lenght = len(index[0])
    for r in range(lenght):
        try:
            axes[1, it].patches[index[0][r]-1].set_fc("red")
        except:
            pass 


plt.tight_layout()
plt.show()

这将为b = a[(a['X3'] < 30)]生成以下内容:

或用于b = a[(a['X3'] > 36)]

我想我会把它放在这里--虽然是小众,但未来可能会对某人有所帮助!

这篇关于更改海运直方图(或PLT)中用于数据选择的条的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆