When comparing multiple categories over time, using different colors for each category makes the chart easier to read. In Matplotlib and pandas, you can create grouped bar charts where each search term or category is displayed with its own color and a legend identifies each series.

Steps to Plot Multiple Colored Bar Charts

  1. Create a list of search terms.
  2. Count the number of records for each search term.
  3. Combine the counts into a single DataFrame.
  4. Plot the DataFrame as a grouped bar chart.
  5. Assign different colors to each category and display a legend.

Example Data

Suppose your DataFrame contains:

  • loc – location name
  • lastmod – date of modification

You want to compare monthly counts for the search terms:

search = "center north south"

Combine Multiple Bar Charts

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

search = "center north south"
terms = search.split()

data = []

for term in terms:
    counts = (
        df[df["loc"].str.contains(term, case=False, na=False)]
        .dropna(subset=["lastmod"])
        .set_index("lastmod")
        .resample("ME")
        .size()
    )
    data.append(counts.rename(term))

# Combine all series into one DataFrame
counts_df = pd.concat(data, axis=1).fillna(0)

labels = counts_df.index.strftime("%b %Y")

fig, ax = plt.subplots(figsize=(18, 5))

colors = sns.color_palette("Set2", n_colors=len(terms))

counts_df.plot(
    kind="bar",
    ax=ax,
    color=colors,
    width=0.8
)

step = 3
ax.set_xticks(range(0, len(labels), step))
ax.set_xticklabels(labels[::step], rotation=45)

ax.set_xlabel("Month")
ax.set_ylabel("Count")
ax.legend(title="Search Term")

plt.tight_layout()
plt.show()

Explanation of the Code

  • The search string is split into individual terms using split().
  • A loop filters the DataFrame for each term and counts the monthly occurrences.
  • Each monthly count is stored as a separate pandas Series.
  • pd.concat() merges all Series into a single DataFrame, where each column represents one search term.
  • fillna(0) replaces missing monthly values with zero.
  • sns.color_palette() generates a unique color for each search term.
  • DataFrame.plot(kind="bar") creates grouped bars, with each color representing a different category.
  • The legend identifies which color corresponds to each search term.

Output

The output is a grouped bar chart where:

  • Each month appears on the x-axis.
  • Each search term is represented by a different colored bar.
  • The y-axis shows the monthly count.
  • A legend explains the color assigned to each search term.

This visualization makes it easy to compare the frequency of multiple search terms across different months.

Example: Multiple Bar Charts with a Single Line Chart

You can also overlay a line chart on top of the grouped bar chart to display an overall trend or total count. This approach is useful when you want to compare individual categories while simultaneously showing the combined monthly total.

A common use case is displaying monthly counts for several search terms as colored bars and plotting the overall monthly total as a black line on a secondary axis, making it easy to identify both category-specific and overall trends.