python -seaborn : share X label not working as expected

标签 python seaborn boxplot

我正在处理一个显示两点之间关系的数据集,例如公交车站。例如,我们有巴士站 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)

enter image description here

最佳答案

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

order, hue_order : lists of strings, optional
Order to plot the categorical levels in, otherwise the levels are inferred from the data objects.

像这样使用

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

enter image description here

关于 python -seaborn : share X label not working as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46133826/

相关文章:

python - 如何创建具有多个颜色图的热图?

python - 创建散点图矩阵时如何更改seaborn中的颜色优先级

r - 如何将文本添加到 r 中的绘图箱线图中

python - 如何将三个列表 x,y,z 转换为矩阵 z[x,y]?

python - 如何编写一个像 list(zip(...)) 一样工作的函数?

python - seaborn distplot y 轴密度值在几个 bin 上高于 1.0

python-3.x - 在Seaborn箱图中更改X轴标签

python - 如何将 seaborn boxplot 须基于百分位数?

python - 嵌套的 for 循环和字典在字符串中查找值的出现

python - 循环的时间复杂度是多少?