Stacked bar charts are a handy way of conveying a lot of information in a single visual and pandas makes it pretty easy to generate these charts by setting the stacked property to True in the plot function.

As great as this operation is, though, you still need to do some cleanup work on your chart afterwards. In this post, I’ll talk about how I clean up the legend generated in a stacked bar chart. For my example, I’ll take a small sample of email data I gathered recently from one of my email accounts.

Bring in the data and do some standard cleanup

import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline


df_email = pd.read_csv('./data/email_data.csv', names=['email_ts', 'subject', 'category'])

df_email['email_ts'] = pd.to_datetime(df_email.email_ts)
df_email['email_dt'] = df_email.email_ts.dt.date
df_email['dow'] = df_email.email_ts.dt.dayofweek
# just look at 30 or so days of data
df_email = df_email[(df_email.email_ts>'2020-04-14 00:00:00') & (df_email.email_ts<'2020-05-15 00:00:00')]

As a standard practice, whenever I have timestamp data, I always add a “date” column and a “day of week” column. If my data spans multiple months, I’ll even add a “month” column. These columns make is much easier to group the data by day, day of week, and month later on.

Chart the data

Here’s a quick glimpse of the data in my dataset:

fig, ax = plt.subplots(figsize=(12,8))
title = 'Email counts: {0:%d %b %Y} - {1:%d %b %Y}'.format(df_email.email_dt.min(), df_email.email_dt.max())

df_email[['email_dt','dow']].groupby('email_dt').count().plot(ax=ax)
_ = ax.set_title(title)
_ = ax.set_xlabel('Date')
_ = ax.set_ylabel('Email Count')
_ = fig.autofmt_xdate()

Now, create a stacked bar chart

Here’s the type of code I normally write to generate a stacked bar chart:

fig, ax = plt.subplots(figsize=(12,8))
title = 'Email counts: {0:%d %b %Y} - {1:%d %b %Y}'.format(df_email.email_dt.min(), df_email.email_dt.max())

df_email[['email_dt','category','dow']].groupby(['email_dt','category']).count().unstack().\
    plot(stacked=True, kind='bar', ax=ax)

_ = ax.set_title(title)
_ = ax.set_xlabel('Date')
_ = ax.set_ylabel('Email Count')
_ = ax.set_ylim([0,46])  # just to give some space to the legend
_ = fig.autofmt_xdate()
Decent chart, but what’s the deal with that legend?

So, this chart is pretty decent, but that legend needs work. The good news is that three lines of code will clean it up nicely. Here’s my better version:

fig, ax = plt.subplots(figsize=(12,8))
title = 'Email counts: {0:%d %b %Y} - {1:%d %b %Y}'.format(df_email.email_dt.min(), df_email.email_dt.max())

df_email[['email_dt','category','dow']].groupby(['email_dt','category']).count().unstack().\
    plot(stacked=True, kind='bar', ax=ax)

_ = ax.set_title(title)
_ = ax.set_xlabel('Date')
_ = ax.set_ylabel('Email Count')
_ = fig.autofmt_xdate()
_ = ax.set_ylim([0,46])  # just to give some space to the legend

original_legend = [t.get_text() for t in ax.legend().get_texts()]
new_legend = [t.replace('(dow, ', '').replace(')', '') for t in original_legend]
_ = ax.legend(new_legend, title='Category')
Nicer looking legend

So, with stacked bar charts, this is one approach I take to make the end product look a little nicer. In upcoming posts, I’ll show even more techniques to clean up your charts.