在python中创建条件轴标签

时间:2019-02-21 18:03:51

标签: python matplotlib seaborn

我有一个像这样的数据框:

Status      hour
Cancelled   11
NA          11
Cancelled   22
NA          10
Cancelled   7
NA          6
NA          22
Cancelled   6

我要创建一个如下图所示的图形,我想根据所选的时隙标记x轴:

#   0-4 --> Mid Night
#   4-8 --> Early Morning
#   8-12 --> Morning
#   12-16 --> After noon
#   16-20 --> Evening
#   20-24 --> Night

预期图形(假设图形的橙色部分显示NA,蓝色显示已取消): enter image description here

我完全不知道如何实现这一目标,任何线索将不胜感激。

1 个答案:

答案 0 :(得分:1)

要开始这个问题,您首先需要计算每个时间间隔内'Cancelled''nan'的所有出现次数。但在此之前,我将设置一些数据:

from io import StringIO
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_fwf(StringIO("""
Status      hour
Cancelled   1
Cancelled   11
NA          11
NA          13
Cancelled   22
NA          10
Cancelled   17
Cancelled   18
Cancelled   19
Cancelled   7
NA          6
NA          22
Cancelled   6
"""), header=1)

好的,现在我们可以遍历时间类别并进行计数

values = {}
for i in range(6):
    values[i] = {}

    status = df.loc[(df['hour'] > i*4) & (df['hour'] <= (i+1)*4), 'Status']

    values[i]['Cancelled'] = status.str.contains('Cancelled').sum()
    values[i]['nan'] = status.isnull().sum()

做图就没什么用了

fig, ax = plt.subplots(1, 1)

for i in range(6):
    ax.bar(i, values[i]["Cancelled"], color='C0')
    ax.bar(i, values[i]["nan"], color='C1', bottom=values[i]["Cancelled"])

ax.set_xticks(np.r_[:6])
ax.set_xticklabels(['Mid night',
                   'Early Morning',
                   'Morning',
                   'After noon',
                   'Evening',
                   'Night'], rotation=45)

fig.tight_layout()

这给了我以下内容:

enter image description here