Skip to content Skip to sidebar Skip to footer

Plotting Dataframes Containing Hh:mm Format In A Single Figure Matplotlib

My question (written at the end below) is related to plotting histograms of two DataFrames in different sub-figures (Situation 1 below) as compared to plotting them in the same fig

Solution 1:

You can also use sns's powerful hue:

# convert to time
df_in.time = pd.to_datetime(df_in.time)
df_out.time = pd.to_datetime(df_out.time)

# mark the series/dataframe and join
df_in['df'] = 'df_in'
df_out['df'] = 'df_out'df = pd.concat((df_in,df_out))

# groupby hours:df = df.groupby(['df',df.time.dt.hour]).size().reset_index()

# plot with sns
plt.figure(figsize=(10,6))
sns.barplot(x='time', 
            y=0,
            hue='df', 
            dodge=False,
            data=df)
plt.show()

Output:

enter image description here


Edit: to plot the bars with x-axis being from 7 to 23, we can reindex before plot:

df = (df.groupby(['df', df.time.dt.hour]).size()
        .reset_index(level=0).reindex(range(7,24))
        .reset_index()
     )

And the sns barplot gives:

enter image description here

Solution 2:

A numeric bar plot could look like this:

import pandas as pd
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
import matplotlib.pyplot as plt
from matplotlib.dates import HourLocator, DateFormatter


# Defining the two DataFrames
df_in = pd.DataFrame({'time': ['12:20', '12:06', '11:30', '11:03', '10:44', '10:50', '11:52', 
                               '12:21', '9:58', '12:43','12:56', '13:27', '12:14',]})

df_out = pd.DataFrame({'time': ['19:40', '19:44', '19:21', '20:37', '20:27', '18:46', '19:42', 
                                '18:12', '19:08', '21:09', '18:37', '20:34', '20:15']})

colors = ['r', 'b']
titles = ['df-in', 'df-out']

fig, ax = plt.subplots(figsize=(7, 3))


for df, c, t inzip([df_in, df_out], colors, titles):
    df['hour'] = pd.to_datetime(df['time'], format='%H:%M')
    df.set_index('hour', drop=False, inplace=True)
    df = df['hour'].groupby(pd.Grouper(freq='60Min')).count()
    df.index = pd.to_datetime(df.index)
    ax.bar(df.index, df.values, width=1/24/2, color=c, label=t)

ax.xaxis.set_major_locator(HourLocator())
ax.xaxis.set_major_formatter(DateFormatter("%H:%Mh"))
ax.set_xlim(pd.to_datetime(["1900-01-01 07:00", "1900-01-01 23:00"]))
plt.setp(ax.get_xticklabels(), rotation=90)
plt.tight_layout()
plt.show() 

enter image description here

Post a Comment for "Plotting Dataframes Containing Hh:mm Format In A Single Figure Matplotlib"