【问题标题】:python - seaborn: share X label not working as expectedpython - seaborn:共享 X 标签未按预期工作
【发布时间】:2017-09-09 18:25:58
【问题描述】:

我正在处理一个显示两点之间关系的数据集,例如公交车站。例如,我们有巴士站 A、B、C 和 D。

我想制作直方图,显示每个公交车站到达其他 3 个公交车站需要多长时间。

显然,从 A 到 A 没有时间,因此应该是空白的。

当我绘制它时,我看到第一行显示 B C D,第二行显示 A、C、D 等。列未对齐,并且每行中的颜色不代表同一列。

如果我添加 sharex = True,它只会删除每个轴上的 x 标签。这显然不是我想在这里看到的。

我希望看到 A、B、C、D 顺序的 4 列。当它是 A 到 A 时,它应该是空白的,并且颜色应该是一致的。

有谁知道如何做到这一点?

import pandas as pd
import numpy as np
import seaborn as sns
%matplotlib inline

time=np.random.randn(1000)
point1 = ['A','B','C','D'] * 250
point2 = ['A'] * 250 + ['B'] * 250 + ['C'] * 250 + ['D'] * 250 

df_time = pd.DataFrame(
    {'point1': point1,
     'point2': point2,
     'time': time
    })
df_time=df_time[df_time['point1']!=df_time['point2']] ##cannot sell to another

fig, ax = plt.subplots(nrows=4, sharey=True)
fig.set_size_inches(12, 16)
for point1i, axi in zip(point1, ax.ravel()):
    sns.boxplot(data=df_time[df_time['point1']==point1i], x='point2', y='time', ax=axi)

【问题讨论】:

    标签: python seaborn boxplot


    【解决方案1】:

    the documentation 看,sns.boxplot 有一个参数order

    order, hue_order : 字符串列表,可选
    为了绘制分类级别,否则级别是从数据对象中推断出来的。

    像这样使用

    sns.boxplot(..., order=['A','B','C','D'])
    

    会给你想要的情节。

    完整代码:

    import pandas as pd
    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    time=np.random.randn(1000)
    point1 = ['A','B','C','D'] * 250
    point2 = ['A'] * 250 + ['B'] * 250 + ['C'] * 250 + ['D'] * 250 
    
    df_time = pd.DataFrame(
        {'point1': point1,
         'point2': point2,
         'time': time
        })
    df_time=df_time[df_time['point1']!=df_time['point2']] ##cannot sell to another
    
    fig, ax = plt.subplots(nrows=4, sharey=True)
    
    for point1i, axi in zip(point1, ax.ravel()):
        sns.boxplot(data=df_time[df_time['point1']==point1i], x='point2', y='time', 
                    ax=axi, order=['A','B','C','D'])
    
    plt.tight_layout()    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 2021-03-11
      • 1970-01-01
      • 2022-08-18
      相关资源
      最近更新 更多