我正在处理一个显示两点之间关系的数据集,例如公交车站。例如,我们有巴士站 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)
最佳答案
从 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()
关于 python -seaborn : share X label not working as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46133826/