0

I have a data frame like this:

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

I want to create a graph as shown below, I want to label the x axis based on the time slot choosen:

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

expected graph(let's assume orange portion of the graph shows NA , blue shows Cancelled): enter image description here

I have absolutely no idea how to achieve this, any clues would be highly appreciated.

1

1 Answer 1

1

To start this question off you first need to count up all of the occurrences of 'Cancelled' and 'nan' in each time interval. But before that, I'll set up some data:

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)

Right, now we can loop over the time categories and do our counting

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

Doing the plot isn't then much work

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

This gave me the following:

enter image description here

Sign up to request clarification or add additional context in comments.

4 Comments

You're welcome, glad I could help! For your own learning process please make sure you understand what I've done and why it works :)
Thank you so much again! Can you please tell me the best book or the best online tutorials for a beginner. I am struggling to learn python :)
You're welcome. I guess it really depends what you want to use Python for. My go to reference has always been this book. However, by the same author, for a complete beginner this text may be more appropriate
I need to learn python for data science. Thank you so much again for all your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.